【Leetcode】Reverse Vowels of a String
2016-05-27 23:46
323 查看
题目链接:https://leetcode.com/problems/reverse-vowels-of-a-string/
题目:
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".
思路:
easy
算法:
public String reverseVowels(String s) {
char c[] = s.toCharArray();
Set<String> vowels = new HashSet<String>();
vowels.add("a");
vowels.add("e");
vowels.add("i");
vowels.add("o");
vowels.add("u");
vowels.add("A");
vowels.add("E");
vowels.add("I");
vowels.add("O");
vowels.add("U");
int v1=-1,v2=-1;
for(int start=0,end=c.length-1;start<end;){
if(v1==-1){
if(vowels.contains(c[start]+""))
v1 = start;
else
start++;
}
if(v2==-1){
if(vowels.contains(c[end]+""))
v2 = end;
else
end--;
}
if(v1!=-1&&v2!=-1){
char tmp = c[v1];
c[v1] = c[v2];
c[v2] = tmp;
v1 = -1;
v2 = -1;
start++;
end--;
}
}
return new String(c);
}
题目:
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".
思路:
easy
算法:
public String reverseVowels(String s) {
char c[] = s.toCharArray();
Set<String> vowels = new HashSet<String>();
vowels.add("a");
vowels.add("e");
vowels.add("i");
vowels.add("o");
vowels.add("u");
vowels.add("A");
vowels.add("E");
vowels.add("I");
vowels.add("O");
vowels.add("U");
int v1=-1,v2=-1;
for(int start=0,end=c.length-1;start<end;){
if(v1==-1){
if(vowels.contains(c[start]+""))
v1 = start;
else
start++;
}
if(v2==-1){
if(vowels.contains(c[end]+""))
v2 = end;
else
end--;
}
if(v1!=-1&&v2!=-1){
char tmp = c[v1];
c[v1] = c[v2];
c[v2] = tmp;
v1 = -1;
v2 = -1;
start++;
end--;
}
}
return new String(c);
}
相关文章推荐
- wchar_t 与 unsigned short 类型不匹配问题
- UGUI制作无限循环List列表
- 【Leetcode】Integer Break
- Trouble Shoot - The prefix "context" for element "context:component-scan" is not bound. Spring MVC
- 据说年薪30万的Android程序员必须get的技能
- 【Leetcode】Counting Bits
- Android点击除EditText外地方隐藏软键
- 麦肯锡七步成诗法学习笔记简记以及案例分析(附参考资料可下载)
- VAO,VBO绘图方式及GLSL传值
- Java基础回顾 : 正则表达式
- EntityFramework codefirst
- DevExpress官方汉化文件对界面进行汉化的过程
- java 强引用,软引用,弱引用,虚引用
- iOS对象序列化和反序列化
- xml schema约束入门(1)
- Android 通过注册广播,实时监听网络连接与断开状态的变化
- 公众号微信支付开发
- 有钱没钱
- hdu-2680-Choose the best route
- C++ 马克思手稿问题(暴力循环)