PROGRAMING/C#

[Algorithm] Reverse each word

donghunl 2024. 5. 2. 05:14
반응형

Question :

Convert input strint to new string with each word reversed.

No punctuation in the string, each word separated by spaces.

Casing should remain the same.

 

주어진 문장을 각각 거꾸로 해서 다시 출력하는 문제입니다.

 

Solution :

 

이 문제를 풀기 위해서는 valildation과 normalization 그리고 search 알고리즘에 관한 지식이 필요합니다.

먼저 입력값이 null거나 빈문자열인지를 확인한후 스페이스로 구분하여 배열에 저장하는 과정을 거칩니다.

그런후 입력된 값을 거꾸로 반환 시켜 새로운 문자을 완성시킵니다.

using System.Text;

public class HelloWorld
{
    static String ReverseEachWord(String input)
    {
        if (string.IsNullOrEmpty(input)) { // 입력값 체크 Validation
            return input;
        }

        StringBuilder result = new StringBuilder();
        string[] ar = input.Splict(" "); // 입력값을 스페이스로 구분하여 배열에 저장

        for (int i = 0;i < arr.Length; i++) {
            result.Append(Reverse(arr[i]));
            if (i != arr.Length - 1) {
                result.Append(" ");
            }
        }

        return result;
    }
    
    static String Reverse(String input) {
    	if (string.IsNullOrEmpty(input)) { // 입력값 체크 Validation
        	return input;
        }
        
        StringBuilder reversed = new StringBuilder();
        
        for (int i = input.Length - 1; i >= 0; i--) { 
        	reversed.Append(input[i]); // 한자 한자 꺼구로 해서 연결시킴
        }
        
        return reversed.ToString();
    }
    
    static void Main(string[] args)
    {
    	Console.WriteLine(ReverseEachWord("sally is a great worker"));
        Console.WriteLine(ReverseEachWord(null));
        Console.WriteLine(ReverseEachWord("racer racecar madam"));
        Console.WriteLine(ReverseEachWord("what can I do today"));
        Console.WriteLine(ReverseEachWord(" "));
    }
}

 

실행한 결과:

yllas si a taerg rekrow

 

recar racecar madam

tahw nac I od yadot

 

 

반응형

'PROGRAMING > C#' 카테고리의 다른 글

[Algorithm] Sort Colors  (3) 2024.05.04
[Algorithm] The smallest possible integer after removing k  (2) 2024.05.04
[Algorithm] Valid Palindrome  (69) 2024.04.30
[Algorithm] Palindrome Number  (92) 2024.04.27
[Algorithm] Integer to Roman  (100) 2024.04.25