Reverse Vowels of a String
https://leetcode.com/problems/reverse-vowels-of-a-string/description/
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Given s = "hello", return "holle".
Example 2:
Given s = "leetcode", return "leotcede".
Note:
The vowels does not include the letter "y".
Thoughts
题目要求把元音前后对调,因此需要两个指针分别指向需要对调的元素。
Code
class Solution {
private boolean isVowel(String s, int i) {
String vowel = "aeiouAEIOU";
return vowel.contains(s.charAt(i) + "");
}
public String reverseVowels(String s) {
StringBuilder sb = new StringBuilder(s);
int l = 0, r = s.length() - 1;
while (l < r) {
if (!isVowel(s, l)) {
l++;
}
if (!isVowel(s, r)) {
r--;
}
if (isVowel(s, l) && isVowel(s, r)) {
sb.setCharAt(l, s.charAt(r));
sb.setCharAt(r, s.charAt(l));
l++;
r--;
}
}
return sb.toString();
}
}
Analysis
时间复杂度O(n).
Last updated
Was this helpful?