Notice
Recent Posts
Recent Comments
Link
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Tags
more
Archives
Today
Total
관리 메뉴

개발 일지

1417. Reformat The String (문자열 재포맷) 본문

코딩 테스트/LeetCode

1417. Reformat The String (문자열 재포맷)

포카리tea 2024. 11. 6. 17:37
영숫자 문자열 s가 제공됩니다. (영숫자 문자열은 소문자 영어와 숫자로 구성된 문자열입니다.). 문자열의 순열을 찾아야 하는데, 문자열 뒤에는 문자가 없고 숫자 뒤에는 다른 숫자가 없습니다. 즉, 인접한 두 문자의 유형이 동일합니다. 재포맷된 문자열을 반환하거나 문자열을 재포맷할 수 없는 경우 빈 문자열을 반환합니다.



예시 1:

입력: s = "a0b1c2"
출력: "0a1b2c"
설명: "0a1b2c"에서 동일한 유형을 가진 인접한 두 문자가 없습니다. "a0b1c2", "0a1b2c", "0c2a1b"도 유효한 순열입니다.

 

예시 2:

입력: s = "leetcode"
출력: ""
설명: "leetcode"에는 문자만 있으므로 숫자로 구분할 수 없습니다.

 

예시 3:

입력: s = "1229857369"
출력: ""
설명: "1229857369"는 숫자만 있으므로 문자로 구분할 수 없습니다.

 

조건:

  • 1 <= s.length <= 500
  • s는 소문자 영어 문자 및/또는 숫자로만 구성됩니다.

 

정답:

public class Solution {
    public string Reformat(string s) {
        List<char> result = new List<char>();
        List<char> chars = new List<char>();
        List<char> ints = new List<char>();
        
        for (int i = 0; i < s.Length; i++)
        {
            if ((int)s[i] > (int)'9')
            {
                chars.Add(s[i]);
            }
            else
            {
                ints.Add(s[i]);
            }
        }

        if (Math.Abs(chars.Count - ints.Count) <= 1)
        {
            chars.Sort();
            ints.Sort();

            bool switchFirst = true;

            if (chars.Count > ints.Count)
            {
                switchFirst = false;
            }
            
            for (int i = 0; i < s.Length; i++)
            {
                if (switchFirst)
                {
                    result.Add(ints[0]);
                    ints.RemoveAt(0);
                }
                else
                {
                    result.Add(chars[0]);
                    chars.RemoveAt(0);
                }

                switchFirst = !switchFirst;
            }

            return new string(result.ToArray());
        }
        
        return "";
    }
}

해설: s를 char와 int형으로 분리합니다.

분리한 후 길이를 비교해서 길이가 2개 이상 차이나면 번갈아가면서 문자열을 생성할 수 없기 때문에 ""를 return하고 길이가 긴 char List를 우선적으로 앞에 배치하여 result를 생성하고 return합니다.