LeetCode【345】反转字符串中的元音字母

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

示例 1:

输入: “hello”
输出: “holle”
示例 2:

输入: “leetcode”
输出: “leotcede”
说明:
元音字母不包含字母"y"。

public class LeetCode345 {

    public String reverseVowels(String s) {
        if(s == null)
            return null;
        int l = 0;
        int r = s.length()-1;
        char[] str = s.toCharArray();
        while(l<r){
            if(isVowel(s.charAt(l)) && isVowel(s.charAt(r))){
                char temp = str[l];
                str[l] = str[r];
                str[r] = temp;
                l++;
                r--;
            }
            if(!isVowel(str[l])){
                l++;
            }
            if(!isVowel(str[r])){
                r--;
            }
        }
        return new String(str);
    }

    boolean isVowel(char c){
        return c=='a' || c == 'e'|| c== 'i' || c== 'o' || c== 'u' ||
                c=='A' || c == 'E'|| c== 'I' || c== 'O' || c== 'U' ;
    }
}
发布了55 篇原创文章 · 获赞 14 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq422243639/article/details/103743816