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

说明:这里是翻转字符串中的原音,

比如字符串是:a, e, i , o, u

你们翻转过来就是 u, o, i, e, a; 第一个和最后一个,第二个和到二个。

遍历是最简单的方法,设置 left和right,两个坐标,分别从数组的头部和尾部逐渐开始遍历,遇到元音停下,遇到非元音分别往中间靠拢,直到两边都遇到元音,交换,再同时靠拢,终止条件是left>=right。

代码:

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);
    }
}

猜你喜欢

转载自rayfuxk.iteye.com/blog/2302809