Reverse Vowels of a String

lc 345 Reverse Vowels of a String

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

Example 1: Given s = "hello", return "holle".

Example 2: Given s = "leetcode", return "leotcede".

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

两个指针,一个前一个后,当两个都是元音的时候,交换位置即可。

public class Solution {
    public String reverseVowels(String s) {
        if(s == null || s.length() <= 1) return s;
        String vowels = "aeiouAEIOU";
        int start = 0;
        int end = s.length() - 1;
        char[] arr = s.toCharArray();
        while(start < end){
            while(vowels.indexOf(s.charAt(start)) == -1 && start < end){
                start++;
            }
            if(start == end) return new String(arr);
            while(vowels.indexOf(s.charAt(end)) == -1 && start < end){
                end--;
            }
           if(start == end) return new String(arr);
           char temp = arr[start];
           arr[start] = arr[end];
           arr[end] = temp;
           start++;
           end--;
        }
        return new String(arr);
    }
}

results matching ""

    No results matching ""