programmers
[JAVA] 문자열 잘라서 정렬하기
아잠만_
2024. 6. 28. 16:04
문자열 myString이 주어집니다. "x"를 기준으로 해당 문자열을 잘라내 배열을 만든 후 사전순으로 정렬한 배열을 return 하는 solution 함수를 완성해 주세요.
단, 빈 문자열은 반환할 배열에 넣지 않습니다.
import java.util.*;
class Solution {
public List<String> solution(String myString) {
List<String> list = new ArrayList<>();
String temp = "";
for(int i=0; i<myString.length();i++){ // myString 순서대로
if(myString.charAt(i)=='x'&&!temp.equals("")){
// x이고 temp이 공백이 아닐때 (저장)
list.add(temp);
temp = "";
} else if(myString.charAt(i)!='x'){
// x가 아닐 때 temp저장
temp += ""+myString.charAt(i);
}
}
if(!temp.equals("")){
// 반복문이 끝나고 temp에 저장할 단어가 있을 때 추가
list.add(temp);
temp = "";
}
// 정렬
Collections.sort(list);
return list;
}
}