Reverse Vowels of a String Leetcode
Posted 璨璨要好好学习
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode Reverse Vowels of a String
LeetCode 345. Reverse Vowels of a String
LeetCode #345 Reverse Vowels of a String
[LeetCode]345 Reverse Vowels of a String