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

编写一个函数,以字符串作为输入,反转该字符串中的元音字母。

 

示例 1:

输入:"hello"
输出:"holle"
示例 2:

输入:"leetcode"
输出:"leotcede"
 

提示:

元音字母不包含字母 "y" 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-vowels-of-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

采用双指针,分别从前和后遍历字符串,遇到元音则交换,否则不交换。

    public String reverseVowels(String s) {
        if (s == null || s.length() < 2) {
            return s;
        }
        char[] arr1 = s.toCharArray();
        int length = s.length();
        char[] arr2 = new char[length];
        int st = 0;
        int end = length - 1;
        while (st <= end) {
            char a = arr1[st];
            char b = arr1[end];
            boolean b1 = (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u' 
          || a == 'A' || a == 'E' || a == 'I' || a == 'O' || a == 'U'); boolean b2 = (b == 'a' || b == 'e' || b == 'i' || b == 'o' || b == 'u'
          || b == 'A' || b == 'E' || b == 'I' || b == 'O' || b == 'U'); if (b1 && b2) { arr2[st] = arr1[end]; arr2[end] = arr1[st]; st++; end--; } if (!b1) { arr2[st] = arr1[st]; st++; } if (!b2) { arr2[end] = arr1[end]; end--; } } return String.valueOf(arr2); }

写的有点繁冗,不过事件复杂的还可以。

posted @ 2021-04-16 23:23  旺仔古李  阅读(59)  评论(0编辑  收藏  举报