345. Reverse Vowels of a String翻转字符串中的元音字母

时间:2022-05-22 17:27:58

[抄题]:

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".

[暴力解法]:抽出来再放回去:不现实

时间分析:

空间分析:

[优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

[一句话思路]:

直接一个字符串甩过来,String vowels = "aeiouAEIOU";再切碎成数组即可

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

先调指针再交换。和qucik sort的区别:从外围开始,能换就换

345. Reverse Vowels of a String翻转字符串中的元音字母

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分钟肉眼debug的结果]:

[总结]:

直接一个字符串甩过来,String vowels = "aeiouAEIOU";再切碎成数组即可

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

双引号,用来引用字符串,单引号用来表示单个字符。字符+""双引号变成字符串

[关键模板化代码]:

先换指针,再交换值:

while (start < end) {
//adjust start, end
while (start < end && !vowels.contains(chars[start] + "")) {
start++;
}
while (start < end && !vowels.contains(chars[end] + "")) {
end--;
}
//exchange
char temp = chars[start];
chars[start] = chars[end];
chars[end] = temp;
//push to move on
start++;
end--;
}

[其他解法]:

hashset 需要一个个字母地加,不如字符串一刀切

[Follow Up]:

[LC给出的题目变变变]:

[代码风格] :

class Solution {
public String reverseVowels(String s) {
//cc
if (s == null) {
return s;
}
//ini
String vowels = "aeiouAEIOU";
char[] chars = s.toCharArray();
int start = 0, end = s.length() - 1; while (start < end) {
//adjust start, end
while (start < end && !vowels.contains(chars[start] + "")) {
start++;
}
while (start < end && !vowels.contains(chars[end] + "")) {
end--;
}
//exchange
char temp = chars[start];
chars[start] = chars[end];
chars[end] = temp;
//push to move on
start++;
end--;
} //return
return new String(chars);
}
}