当前位置:网站首页>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
边栏推荐
猜你喜欢
随机推荐
程序员都应该知道的URI,一文帮你全面了解
To introduce to you, this is my flow chart software—— draw.io
表连接
Octave基本语法
新手入坑指南:工作原因“重启”Deepin系统,发现真的香啊
Decorator (1)
小议缓冲区溢出
AQS 都看完了,Condition 原理可不能少!
Dynamic programming: maximum subarray
Factory Pattern模式(简单工厂、工厂方法、抽象工厂模式)
Introduction skills of big data software learning
Looking for a small immutable dictionary with better performance
服务器性能监控神器nmon使用介绍
写时复制集合 —— CopyOnWriteArrayList
选择排序
你有没有想过为什么交易和退款要拆开不同的表
六家公司CTO讲述曾经历的“宕机噩梦”
大数据软件学习入门技巧
VIM Introduction Manual, (vs Code)
Pipedrive如何在每天部署50+次的情况下支持质量发布?






