Reverse Vowels of a String

mac2022-06-30  67

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

 

vowels:元音aeiou

 

解法:two pointers

public class Solution { public String reverseVowels(String s) { String vowel = "aeiouAEIOU"; int start = 0; int end = s.length()-1; char[] chars = s.toCharArray(); while(start<end) { while(start<end&&!vowel.contains(chars[start]+"")) { start++; } while(start<end&&!vowel.contains(chars[end]+"")) { end--; } char temp = chars[start]; chars[start]=chars[end]; chars[end]=temp; start++; end--; } return String.valueOf(chars); } } chars[end]+"" 这里加上“”很重要,不然会出以下错误: error: incompatible types: char cannot be converted to CharSequence

 

转载于:https://www.cnblogs.com/hygeia/p/5700019.html

最新回复(0)