345. Reverse Vowels of a String
来源:互联网 发布:惠普清零软件 编辑:程序博客网 时间:2024/06/05 08:17
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".
题目意思:交换一个字符串中的元音字母,例如"hello"转换为“holle”,如果有多个元音字母,如“leetcode”,第一个元音字母和最后一个交换,第二个和倒数第二个交换.....
可以用首尾两个指针,当前后两个字符都是元音字母时交换,并且首指针向后移动,尾指针向前移动,如果只有首指针指的是元音字母而尾指针指的是非元音字母,则尾指针向前移动,否则首指针向后移动
int left = 0; int right = s.length()-1; char [] arr = s.toCharArray(); while(left<right){ if(isVowels(s.charAt(left))&&isVowels(s.charAt(right))){ char tmp = arr[left]; arr[left] = arr[right]; arr[right] = tmp; left++; right--; }else if(isVowels(arr[right])){ //如果只是左边的是元音字母,右边不是,那么向左移一位 ++left; }else{ //否则,左边的向右移一位 --right; } }// return new String(arr); //把字符型数组转换成字符串 return String.valueOf(arr); }public static boolean isVowels(char c){return c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||c=='A'||c=='E'||c=='I'||c=='O'||c=='U';}
把字符数组转换成字符串可以用:new String(arr)或者String.valueOf(arr)
(PS:但是有一个问题,为什么另外使用空间新建一个char数组,直接用s.charAt()函数交换不行呢?明天再想。。)
阅读全文
0 0
- String:345. Reverse Vowels of a String
- 345. Reverse Vowels of a String 【E】
- LeetCode 345. Reverse Vowels of a String
- 345. Reverse Vowels of a String
- leetcode-345. Reverse Vowels of a String
- 345. Reverse Vowels of a String
- #leetcode#345. Reverse Vowels of a String
- [leetcode] 345. Reverse Vowels of a String
- 345. Reverse Vowels of a String
- Leetcode:345. Reverse Vowels of a String
- LeetCode *** 345. Reverse Vowels of a String
- 345. Reverse Vowels of a String
- 345. Reverse Vowels of a String
- 345. Reverse Vowels of a String
- 345. Reverse Vowels of a String
- LeetCode.345. Reverse Vowels of a String
- 345. Reverse Vowels of a String
- LeetCode 345. Reverse Vowels of a String
- linux下tftp安装
- C++中字符串的分割
- Softmax 一文看懂Softmax函数
- javaEE项目中WEB-INF目录
- ssm项目下遇到的404问题
- 345. Reverse Vowels of a String
- 9.25学习报告
- 【学习记录】链表的插入
- [NOI2015]寿司晚宴(状态压缩动态规划)
- HTML结构杂记
- 环境配置cocopod
- 招银笔试:100年后有多少只母牛
- Activity异常情况下的生命周期分析
- SQL 两个字段分组,其中一个字段的不同情形,分类并计算数量