[LeetCode-345]Reverse Vowels of a String(java)
2016-10-10 11:08
260 查看
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”.
题意:
写一个函数实现:仅将一个字符串s中的元音字母逆序,并输出改变后的字符串s。
例如:输入hello,输出holle;输入leetcode,输出leotcede
分析:
元音字母:大小写a e i o u
由于字符串一旦定义好了就不能改变,这里先将字符串s转换为字符数组ch
此题思路类似于快速排序算法:
采用两个指针i、j(控制i 小于 j)分别指向字符数组最前端和最后端;
先从左边开始遍历数组,判断数组中对应位置是否是元音字母,如果是,停止遍历;
再从右边开始遍历数组,找到从右往左第一个元音字母的位置;交换左右两边的元音字母,然后继续遍历,直到结束。
Example 1:
Given s = “hello”, return “holle”.
Example 2:
Given s = “leetcode”, return “leotcede”.
Note:
The vowels does not include the letter “y”.
题意:
写一个函数实现:仅将一个字符串s中的元音字母逆序,并输出改变后的字符串s。
例如:输入hello,输出holle;输入leetcode,输出leotcede
相似题:ReverseString
http://blog.csdn.net/xionghuixionghui/article/details/52682732分析:
元音字母:大小写a e i o u
由于字符串一旦定义好了就不能改变,这里先将字符串s转换为字符数组ch
此题思路类似于快速排序算法:
采用两个指针i、j(控制i 小于 j)分别指向字符数组最前端和最后端;
先从左边开始遍历数组,判断数组中对应位置是否是元音字母,如果是,停止遍历;
再从右边开始遍历数组,找到从右往左第一个元音字母的位置;交换左右两边的元音字母,然后继续遍历,直到结束。
//类似于快速排序,使用两个指针分别在左右两边寻找 public class Solution { public String reverseVowels(String s) { //ArrayList中保存元音字母a、e、i、o、u(包含大小写) ArrayList<Character> vowelList=new ArrayList<Character>(); vowelList.add('a'); vowelList.add('e'); vowelList.add('i'); vowelList.add('o'); vowelList.add('u'); vowelList.add('A'); vowelList.add('E'); vowelList.add('I'); vowelList.add('O'); vowelList.add('U'); //String类型一旦定义好就不能改变,所以这里将String类型转换为char数组 //String->Array:str.toCharArray() char[] ch=s.toCharArray(); int i=0; int j=s.length()-1; char temp; while(i<j){ //循环在数组左边寻找元音字母,注意要加上i<j的限制 while(i<j && !vowelList.contains(ch[i])){ i++; } //循环在数组右边寻找元音字母,注意要加上i<j的限制 while(i<j && !vowelList.contains(ch[j])){ j--; } //将左边元音字母与右边元音字母交换 temp=ch[i]; ch[i]=ch[j]; ch[j]=temp; i++; j--; } //Array->String 1.String.valueOf(arr);2.new String(arr);3.sb=new StringBuilder();sb.append(arr[i]); return new String(ch); } }
相关文章推荐
- 【LeetCode】345 Reverse Vowels of a String(java)
- leetcode345 Reverse Vowels of a String java
- LeetCode 345 Reverse Vowels of a String (in java)
- Python [Leetcode 345]Reverse Vowels of a String
- LeetCode345—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
- leetcode note--leetcode 345 Reverse Vowels of a String
- Leetcode Reverse Vowels of a String 345
- 【LeetCode-345】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
- LeetCode 第 345 题(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
- leetcode_345 Reverse Vowels of a String
- Leetcode-345-Reverse Vowels of a String