Given a string s, reverse only all the vowels in the string and return it.
The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once.


s 를 뒤집은 문자열 reverse 를 저장reverse 의 모음을 순서대로 reverseVowels에 저장s 를 순차 탐색하며 해당 문자가 모음(vowels)인 경우 해당 인덱스의 문자를 reverseVowels의 첫번째 문자로 치환하여 result에 저장reverseVowels의 첫번째 문자는 pop 시킨다.result에 저장class Solution {
public String reverseVowels(String s) {
String vowels = "aeiouAEIOU";
StringBuffer reverse = new StringBuffer(s).reverse();
StringBuffer reverseVowels = new StringBuffer();
StringBuffer result = new StringBuffer();
for (int i = 0; i < reverse.length(); i++) {
if(vowels.contains(String.valueOf(reverse.charAt(i)))) {
reverseVowels.append(reverse.charAt(i));
}
}
for (int i = 0; i < s.length(); i++) {
if(vowels.contains(String.valueOf(s.charAt(i)))) {
result.append(reverseVowels.charAt(0));
reverseVowels.deleteCharAt(0);
} else {
result.append(s.charAt(i));
}
}
return result.toString();
}
}
많은 문자열 변수, 비효율적 반복문 사용으로 느린 속도와 메모리 효율이 떨어짐 → two-pointer 를 활용하여 탐색 시간 및 문자열 위치 전환
루프가 끝나면 단어 배열에 모음이 반전된 문자열(reverseVowels)이 포함됨
class Solution {
public String reverseVowels(String s) {
char[] word = s.toCharArray();
int start = 0;
int end = s.length() - 1;
String vowels = "aeiouAEIOU";
while (start < end) {
// Move start pointer until it points to a vowel
while (start < end && vowels.indexOf(word[start]) == -1) {
start++;
}
// Move end pointer until it points to a vowel
while (start < end && vowels.indexOf(word[end]) == -1) {
end--;
}
// Swap the vowels
char temp = word[start];
word[start] = word[end];
word[end] = temp;
// Move the pointers towards each other
start++;
end--;
}
String answer = new String(word);
return answer;
}
}