当前位置:网站首页>leetcode之反转字符串中的元音字母
leetcode之反转字符串中的元音字母
2020-11-08 23:48:00 【go4it】
序
本文主要记录一下leetcode之反转字符串中的元音字母
题目
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
示例 1:
输入:"hello"
输出:"holle"
示例 2:
输入:"leetcode"
输出:"leotcede"
提示:
元音字母不包含字母 "y" 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-vowels-of-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
class Solution {
Set<Character> set = new HashSet(){{
add('a');
add('e');
add('i');
add('o');
add('u');
add('A');
add('E');
add('I');
add('O');
add('U');
}};
public String reverseVowels(String s) {
int i = 0;
int j = s.length() - 1;
char[] chars = s.toCharArray();
while(i < j) {
while (!set.contains(chars[i]) && i<j) {
i++;
}
while (!set.contains(chars[j]) && i<j) {
j--;
}
if (i < j) {
char tmp = chars[i];
chars[i] = chars[j];
chars[j] = tmp;
i++;
j--;
}
}
return new String(chars);
}
}
小结
这里先使用HashSet存放大小写的元音字母,之后使用头尾指针同时对字符串数组进行遍历,当i指向的字符与j指向的字符都是元音时,进行交换同时更新指针,不是元音字符时仅仅更新指针。
doc
版权声明
本文为[go4it]所创,转载请带上原文链接,感谢
https://my.oschina.net/go4it/blog/4708427
边栏推荐
- Tasks of the first week of information security curriculum design (analysis of 7 instructions)
- 经典动态规划:最长公共子序列
- 接口测试工具Eolinker进行post请求
- 移动大数据自有网站精准营销精准获客
- Esockettimeout solution in request in nodejs
- 【云服务】阿里云服务器ECS实例规格那么多,如何选型?最佳实践说明
- 基于链表的有界阻塞队列 —— LinkedBlockingQueue
- 装饰器(一)
- 解决IE、firefox浏览器下JS的new Date()的值为Invalid Date、NaN-NaN的问题
- Python的特性与搭建环境
猜你喜欢
随机推荐
Why need to use API management platform
动态规划答疑篇
动态规划设计:最大子数组
. net core cross platform resource monitoring library and dotnet tool
CMS垃圾收集器
寻找性能更优秀的动态 Getter 和 Setter 方案
Experiment 1 assignment
装饰器(二)
如何让脚本同时兼容Python2和Python3?
200 programmers interview experience, all here
Nodejs中request出现ESOCKETTIMEDOUT解决方案
接口测试工具Eolinker进行post请求
Fiddler无法正常抓取谷歌等浏览器的请求_解决方案
.NET Core 跨平台资源监控库及 dotnet tool 小工具
How to deploy pytorch lightning model to production
C / C + + learning diary: original code, inverse code and complement code
VIM Introduction Manual, (vs Code)
CSP-S 2020 游记
Programmers should know the URI, a comprehensive understanding of the article
实验一作业






