[LeetCode]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".

思路:

写一个函数,string字符串作为参数,将其中的元音字母逆序。提示,y不是元音字母
元音字母指的是aeiou
首先写isVowels函数,判断一个字符是否为元音字母。大小写都要判断
定义left=0,right=s.length()-1
判断字符串的最左端和最右端是否都是元音字母,是的话交换,然后left++,right--。
如果左边是元音字母右边不是,则right--
如果都不是,则left++
直到left>=right
结束循环
返回字符到字符串时,使用 return new String(ch);

 1 public class Solution345 {
 2     public String reverseVowels(String s) {
 3         int left = 0;
 4         int right = s.length()-1;
 5         char[] ch = s.toCharArray();
 6         while(left<right){
 7             if(isVowels(ch[left])&&isVowels(ch[right])){
 8                 char temp = ch[left];
 9                 ch[left] = ch[right];
10                 ch[right] = temp;
11                 left++;
12                 right--;
13             }else if(isVowels(ch[left])){
14                 right--;
15             }else {
16                 left++;
17             }
18         }
19        // return s;
20         return new String(ch);
21     }
22     public boolean isVowels(char c){
23         if(c == 'a'||c == 'e'||c == 'i'||c == 'o'||c == 'u'||c == 'A'||c == 'E'||c == 'I'||c == 'O'||c == 'U'){
24             return true;
25         }else {
26             return false;
27         }
28     
29     }
30     public static void main(String[] args) {
31         // TODO Auto-generated method stub
32         Solution345 solution345 = new Solution345();
33         String s = "hello";
34         System.out.println(solution345.reverseVowels(s));
35     }
36 
37 }
原文地址:https://www.cnblogs.com/zlz099/p/8251727.html