345. 反轉字串中的母音字母(LeetCode)
阿新 • • 發佈:2021-07-08
題目描述
編寫一個函式,以字串作為輸入,反轉該字串中的母音字母。
示例 1:
輸入:"hello"
輸出:"holle"
條件分析
- 原地修改,考慮使用交換;
解題思路(指標對撞)
- 定義兩個指標left和right分別指向字串的首尾,分別移動,直到雙方都找到母音字母,進行交換,並各自相向移動一位,一直到兩個指標相遇;
編碼如下
public String reverseVowels(String s) { char[] cs = s.toCharArray(); int left = 0; int right = cs.length - 1; while (left < right) { if (!isAeiou(cs[left])) { left++; continue; } if (!isAeiou(cs[right])) { right--; continue; } swapChar(cs, left, right); left++; right--; } return new String(cs); } private boolean isAeiou(char c) { return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'; } private void swapChar(char[] cs, int i, int j) { char temp = cs[i]; cs[i] = cs[j]; cs[j] = temp; }