元音字母的字符串反转

题目: 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,需要注意的是大写的也算,所以总共有十个字母。为了减小时间复杂度,在字符串反转这个代码中一般都会利用折半原理,两头往中间凑的方法。
Code:

public class Solution {
    public String reverseVowels(String s) {
       if("".equals(s)||s.length() ==1)
       {
           return s;
       } 
       int length = s.length();
       int leftIndex = 0;
       int rightIndex = length-1;
       char[] array = s.toCharArray();
       do{
           if(isVowel(array[leftIndex]))
           {
               if(!isVowel(array[rightIndex]))
               {
                   rightIndex --;
               }
               if(isVowel(array[rightIndex]))
               {
                 char tmp = array[leftIndex];
                 array[leftIndex] = array[rightIndex];
                 array[rightIndex] = tmp;
                 leftIndex ++;
                 rightIndex--;
               }

           }else
           {
               leftIndex++;
           }

       }while(leftIndexreturn new String(array);
    }

    private 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';
    }
}

你可能感兴趣的:(leetcode)