345.反转字符串中的元音字母


345.反转字符串中的元音字母

给你一个字符串 s ,仅反转字符串中的所有元音字母,并返回结果字符串。

元音字母包括 'a''e''i''o''u',且可能以大小写两种形式出现不止一次。

示例 1:

输入:s = “hello”
输出:”holle”

示例 2:

输入:s = “leetcode”
输出:”leotcede”

提示:

  • 1 <= s.length <= 3 * 105
  • s可打印的 ASCII 字符组成

题解:

class Solution {
    public String reverseVowels(String s) {
        char[] charr = s.toCharArray();
        int i = 0;
        int j = s.length() - 1;
        while (i < j) {
            while (i < s.length() && !isVowel(charr[i])) {
                i++;
            }
            while (j > 0 && !isVowel(charr[j])) {
                j--;
            }
            if (i < j) {
                char temp = charr[i];
                charr[i] = charr[j];
                charr[j] = temp;
                i++;
                j--;
            }
        }

        return new String(charr);
    }
    public boolean isVowel(int n) {
        return "aeiouAEIOU".indexOf(n) >= 0;
    }
}

文章作者: Feliks
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Feliks !
评论
  目录