LeetCode:345. Reverse Vowels of a String

345. Reverse Vowels of a String

Difficulty: Easy

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".

 

Explanation: Here is the original sound in the reversed string,

For example, the string is: a, e, i , o, u

You turn it over and you are u, o, i, e, a; the first and the last, the second and the second.

Traversal is the simplest method. Set left and right, two coordinates, and gradually start traversing from the head and tail of the array, stop when encountering vowels, and move closer to the middle when encountering non-vowels, until both sides meet Vowels, exchange, and approach at the same time, the termination condition is left>=right.

Code:

public class Solution {
    public String reverseVowels(String s) {
        char [] sArray = s.toCharArray ();
        int length = sArray.length;
        int position = -1;
        int left = 0;
        char[] result = {'A', 'E', 'I', 'O', 'U','a', 'e', 'i', 'o', 'u', };
        int right = sArray.length - 1;
        while (left < right) {
            char leftChar = sArray [left];
            int leftifin = Arrays.binarySearch(result,  leftChar);
            if (leftifin < 0) {
                left ++;
            }
            char rigthChar = sArray [right];
            int rightifin = Arrays.binarySearch(result,  rigthChar);
            if (rightifin < 0) {
                right --;
            }
            
            if(leftifin >= 0 && rightifin >= 0) {
                char temp = sArray[left];
                sArray [left] = sArray [right];
                sArray[right] = temp;
                left ++;
                right --;
            }
        }
        return new String(sArray);
    }
}

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326864290&siteId=291194637