상세 컨텐츠

본문 제목

세 개의 구분자

코딩테스트/C#

by MJ_119 2024. 6. 17. 22:31

본문

문제 설명

임의의 문자열이 주어졌을 때 문자 "a", "b", "c"를 구분자로 사용해 문자열을 나누고자 합니다.

예를 들어 주어진 문자열이 "baconlettucetomato"라면 나눠진 문자열 목록은 ["onlettu", "etom", "to"] 가 됩니다.

문자열 myStr이 주어졌을 때 위 예시와 같이 "a", "b", "c"를 사용해 나눠진 문자열을 순서대로 저장한 배열을 return 하는 solution 함수를 완성해 주세요.

단, 두 구분자 사이에 다른 문자가 없을 경우에는 아무것도 저장하지 않으며, return할 배열이 빈 배열이라면 ["EMPTY"]를 return 합니다.


제한사항
  • 1 ≤ myStr의 길이 ≤ 1,000,000
    • myStr은 알파벳 소문자로 이루어진 문자열 입니다.

입출력 예
 
using System;

public class Solution {
    public string[] solution(string myStr) {
        char[] aa = new char[] {'a','b','c'};
        
        // 'a', 'b', 'c'를 구분자로 사용하여 문자열을 분할합니다.
        string[] answer = myStr.Split(aa, StringSplitOptions.RemoveEmptyEntries);
        
        // 분할 결과가 빈 배열인 경우 "EMPTY"를 반환합니다.
        if (answer.Length == 0)
        {
            return new string[] { "EMPTY" };
        }
        
        return answer;
    }
}

 

다른 풀이

using System;

public class Solution {
    public string[] solution(string myStr) {
        string[] answer = myStr.Split(new[] {"a", "b", "c" }, StringSplitOptions.RemoveEmptyEntries);

        if(answer.Length == 0)
        {
            string[] str = {"EMPTY"};
            return str;
        }
        return answer;
    }
}

 

using System;

public class Solution {
    public string[] solution(string myStr) {
        string[] answer = myStr.Split(new char[]{'a', 'b', 'c'}, StringSplitOptions.RemoveEmptyEntries);
        return answer.Length > 0 ? answer : new string[] {"EMPTY"};
    }
}

'코딩테스트 > C#' 카테고리의 다른 글

뒤에서 5등까지  (0) 2024.06.17
빈 배열에 추가, 삭제하기  (0) 2024.06.17
간단한 식 계산하기  (0) 2024.06.17
특정한 문자를 대문자로 바꾸기  (0) 2024.06.17
n보다 커질 때까지 더하기  (0) 2024.06.17

관련글 더보기