Leet Code 알고리즘
(Leet Code c++)Reverse Vowels of a String
naeunchan
2021. 8. 3. 11:12
728x90
반응형
345. Reverse Vowels of a String
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 cases.
Example 1:
Input: s = "hello" Output: "holle"
Example 2:
Input: s = "leetcode" Output: "leotcede"
Constraints:
- 1 <= s.length <= 3 * 105
- s consist of printable ASCII characters.
주어진 문자열 s에서 'a', 'e', 'i', 'o', 'u'에 해당하는 문자를 서로 바꿔줘야 한다.
check() 함수는 현재 문자가 모음(대소문자 포함)인지 확인한다.
front와 back을 통해 맨 앞과 맨 뒤에서부터 탐색을 시작한다.
while문을 통해 탐색 시작.
front < back 이면서, check(answer[front])가 true일 때까지 front를 늘려준다.
back > front 이면서, check(answer[back])이 true일 대까지 back을 줄여준다.
두 while문이 끝나면 서로의 위치를 바꿔주고,
front++, back--를 해주어 계속 이어나가도록 한다.
class Solution {
public:
bool check(char c){
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'){
return true;
}
return false;
}
string reverseVowels(string s) {
string answer = s;
int front = 0, back = s.size() - 1;
while(front <= back){
while(front < back && !check(answer[front])){
front++;
}
while(back > front && !check(answer[back])){
back--;
}
swap(answer[front], answer[back]);
front++;
back--;
}
return answer;
}
};
728x90
반응형