345. Reverse Vowels of a String【Easy】【双指针-反转字符串中的元音字符】

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:

Input: "hello"
Output: "holle"

Example 2:

Input: "leetcode"
Output: "leotcede"

Note:
The vowels does not include the letter "y".

 

Accepted
142,249
Submissions
348,669
 
import java.util.Arrays;
import java.util.HashSet;

class Solution {
    
    private final static HashSet<Character> vowels = 
            new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));
    public String reverseVowels(String s) {
        int len = s.length();
        int i = 0, j = len - 1;
        char[] result = new char[s.length()];
        while(i <= j) {
            char ci = s.charAt(i);
            char cj = s.charAt(j);
            if(!vowels.contains(ci)) {
                result[i++] = ci;
            } else if(!vowels.contains(cj)) {
                result[j--] = cj;
            } else {
                result[i++] = cj;
                result[j--] = ci;
            }
        }
        return new String(result); //
    }
    
}

 

import java.util.Arrays;
import java.util.HashSet;

class Solution {
    public String reverseVowels(String s) {
        if(s == null || s.length() == 0) return s;
        int i = 0, j = s.length() - 1;
        char[] str = s.toCharArray();
        while(i < j) {
            if(isVolwe(str[i]) && isVolwe(str[j])) {
                char tmp = str[i];
                str[i] = str[j];
                str[j] = tmp;
                i++;
                j--;
            }
            else if(!isVolwe(str[i])) {
                i++;
            } else {
                j--;
            }
        }
        return new String(str);
    }
    private boolean isVolwe(char ch) {
        ch = Character.toLowerCase(ch);
        return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'; 
    }
}

 

posted @ 2019-02-24 17:24  Roni_i  阅读(157)  评论(0编辑  收藏  举报