문제 풀기/C#

41. 이상한 문자 만들

kagan-draca 2025. 1. 23. 15:03

 

기본 틀 :

public class Solution {
    public string solution(string s) {
        string answer = "";
        return answer;
    }
}

 

풀이 1) 매개변수 s를 공백 단위로 문자열 배열 형태로 나눈 후 문자열 배열 만큼

            반복문을 수행시켜 해당 문자열에서 Select 문을 사용해 index % 2 가 짝수이면

            대문자로, 홀수이면 소문자로 바꿔준다, 이후, new string.Join(' ', temp)로

            하나의 문자열을 만들어 반환한다.

using System;
using System.Linq;

public class Solution {
    public string solution(string s) 
    {
        string[] temp = s.Split(" ");
           
        for(int i = 0; i < temp.Length; i++)
        {
            temp[i] = new string(temp[i].Select((element, index)=> index % 2 == 0 ? char.ToUpper(element) : char.ToLower(element)).ToArray());
        }
        
        return string.Join(' ',temp);
    }
}

 

풀이 2) 정수형 변수(나는 index로 선언)를 선언하고 문자열 s를 char[] 형식으로

             바꾼 후 반복문을 활용해 문자 배열을 순회한다.

             문자를 순회하면서 index % 2가 짝수이면 문자를 대문자로, 홀수이면 소문자로 바꿔주고

             index++ 해준다. 만약, 문자가 공백일 경우 index = 0으로 초기화하고

             continue로 다음 반복을 진행시켜준다.

 

using System;
using System.Linq;

public class Solution {
    public string solution(string s) 
    {
        int index = 0;
        
        char[] charTemp = s.ToCharArray();
        for(int i = 0; i < charTemp.Length; i++)
        {
            if(charTemp[i] == ' ')
            {
                index = 0;
                continue;
            }
            charTemp[i] = index % 2 == 0 ? char.ToUpper(charTemp[i]) : char.ToLower(charTemp[i]);
            index++;
        }
        return new string(charTemp);
    }
}

 

풀이 1)이 풀이 2) 보다 더 많은 수행시간을 요구하는 이유로는 반복문 안에서

Select()함수를 사용할 경우 결국 해당 문자를 하나하나 순회하기 때문으로 추측된다.

그리고, 풀이 2)에서는 공백이 존재할 경우 continue로 약간이나마 반복 작업을 줄인 것이 

조금이나마 성능 향상에 도움을 도모했다 판단한다.

'문제 풀기 > C#' 카테고리의 다른 글

43. 크기가 작은 부분  (0) 2025.01.24
42. 삼총사  (0) 2025.01.23
40. 3진법 뒤집기  (0) 2025.01.22
39. 최대공약수와 최소공배수  (0) 2025.01.22
38. 직사각형 별찍기  (0) 2025.01.22