您的位置:首页 > 编程语言 > Java开发

【LeetCode】345 Reverse Vowels of a String(java)

2016-05-04 16:15 603 查看
原题

题目要求

解法

原题

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

题目要求

颠倒字符串中元音字母的位置。如”hello”,颠倒第一个和最后一个的位置,就成了”holle”,由于它只有这两个元音字母,所以”holle”就是最终结果。

解法

迭代字符串的元素,找到第n个元音字母后,就尝试去找第len-1-n个元音字母,如果找到就交换位置,再进入下一次循环迭代;如果没找到,则退出循环。代码很像快速排序中处理第n个和第len-1-n个元素的方式。

代码中还有我找到的几个测试用例。

public class Solution {
public String reverseVowels(String s) {
String vowels = "aoeiuAOEIU";
char[] a = s.toCharArray();
int i = 0;
int j = a.length - i - 1;
while (i < j) {
while (i < j && !vowels.contains(a[i] + "")) {
i++;
}
while (i < j && !vowels.contains(a[j] + "")) {
j--;
}
if (i < j) {
char c = a[i];
a[i++] = a[j];
a[j--] = c;
}
}

return new String(a);
}

public static void main(String[] args) {
Solution s = new Solution();
assert(s.reverseVowels("hello").equals("holle"));
assert(s.reverseVowels("leetcode").equals("leotcede"));
assert(s.reverseVowels("").equals(""));
assert(s.reverseVowels("aA").equals("Aa"));
assert(s.reverseVowels("Live on evasions? No I save no evil.").equals("Live on evasIons? No i save no evil."));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: