Algorithm/LeetCode
1859. Sorting the Sentence
JunGi Jeong
2023. 3. 31. 19:19
https://leetcode.com/problems/sorting-the-sentence/
문장은 선행 또는 후행 공백 없이 하나의 공백으로 구분된 단어 목록입니다.
각 단어는 영문 소문자와 대문자로 구성됩니다.
각 단어에 인덱스가 1인 단어 위치를 추가한 다음 문장의 단어를 재정렬하여 문장을 섞을 수 있습니다.
예를 들어 "This is a sentence"라는 문장은
"sentence4 a3 is2 This1" 또는 "is2 sentence4 This1 a3"로 섞일 수 있습니다.
9개 이하의 단어를 포함하는 섞인 문장 s가 주어지면 원래 문장을 재구성하고 반환합니다.
구현
class Solution {
public String sortSentence(String s) {
String[] arr = s.split(" ");
String[] res = new String[arr.length];
for(int idx = 0; idx < arr.length; idx++) {
int k = arr[idx].length()-1;
int m = arr[idx].charAt(k) - '0';
res[m-1] = arr[idx].substring(0,k);
}
StringBuilder sb = new StringBuilder();
for(int idx = 0; idx < res.length; idx++) {
sb.append(res[idx]+ " ");
}
return (sb.toString()).trim();
}
}
class Solution
{
public String sortSentence(String s)
{
String[] ans = new String[s.split(" ").length];
for(String st: s.split(" "))
{
ans[st.charAt(st.length()-1) - '1'] = st.substring(0,st.length()-1);
}
return String.join(" ",ans);
}
}