首页 > 代码库 > Reverse Vowels of a String Leetcode
Reverse Vowels of a String Leetcode
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".
这道题一开始没想到stirng可以变成char的array,就做复杂了。。。边界的时候还需要挺注意的。
public class Solution { public String reverseVowels(String s) { if (s == null || s.length() == 0) { return s; } int left = 0, right = s.length() - 1; Set<Character> vowel = new HashSet<>(Arrays.asList(new Character[] {‘a‘, ‘e‘, ‘i‘, ‘o‘, ‘u‘, ‘A‘, ‘E‘, ‘I‘, ‘O‘, ‘U‘})); StringBuilder newS = new StringBuilder(); while (left < s.length()) { while (left < s.length() && !vowel.contains(s.charAt(left))) { newS.append(s.charAt(left)); left++; } while (right >= 0 && !vowel.contains(s.charAt(right))) { right--; } if (right >= 0) { newS.append(s.charAt(right)); } left++; right--; } return newS.toString(); } }
如果变成char array就很好做了
public class Solution { public String reverseVowels(String s) { if (s == null || s.length() == 0) { return s; } int left = 0, right = s.length() - 1; Set<Character> vowel = new HashSet<>(Arrays.asList(new Character[] {‘a‘, ‘e‘, ‘i‘, ‘o‘, ‘u‘, ‘A‘, ‘E‘, ‘I‘, ‘O‘, ‘U‘})); char[] str = s.toCharArray(); while (left < right) { while (left < right && !vowel.contains(str[left])) { left++; } while (left < right && !vowel.contains(str[right])) { right--; } char tmp = str[left]; str[left] = str[right]; str[right] = tmp; left++; right--; } return new String(str); } }
需要注意的是char数组转成string有这两种方法:
new String(charArray);
String.valueOf(charArray);
Reverse Vowels of a String Leetcode
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。