345. Reverse Vowels of a String

不定期更新leetcode解题java答案。

采用pick one的方式选择题目。 

题意为将给定字符串中的元音字符逆序处理返回。

思路为从前向后、从后向前进行字符检索,若为元音则交换顺序,否则不变。代码如下:

 1 public class Solution {
 2     public String reverseVowels(String s) {
 3         char[] chs = new char[s.length()];
 4         int start = 0, end = s.length() - 1;
 5         
 6         while(start <= end){
 7             char startChar = s.charAt(start), endChar = s.charAt(end);
 8             if(isVowel(startChar) && isVowel(endChar)){
 9                 chs[start] = endChar;
10                 chs[end] = startChar;
11                 start++;
12                 end--;
13             }else{
14                 if(!isVowel(startChar)){
15                     chs[start] = startChar;
16                     start++;
17                 }
18                 if(!isVowel(endChar)){
19                     chs[end] = endChar;
20                     end--;
21                 }
22             }
23         }
24         
25         StringBuilder sb = new StringBuilder();
26         for(int i = 0; i < s.length(); i++)
27             sb.append(chs[i]);
28             
29         return sb.toString();
30     }
31     
32     public boolean isVowel(char ch){
33         return ch == 'a' || ch == 'e' || ch == 'o' || ch == 'i' || ch == 'u'
34             || ch == 'A' || ch == 'E' || ch == 'O' || ch == 'I' || ch == 'U';
35     }
36 }

 

posted @ 2016-10-09 16:03  zslhq~  阅读(116)  评论(0编辑  收藏  举报