Leetcode解题笔记-Reverse Words in a String
2015-08-07 03:45
323 查看
题目要求:
给定一个字符串由不同单词组成,返回其相反顺序,中间可能有多余字符:
例如:
Given s = "
return "
个人解法:
1.暴力,主要是对于两个单词中间存在多个空格的处理。
2. 利用栈来存储临时变量。
3.缺点,空间利用太大
代码:
public String reverseWords(String s) {
Stack<String> stack = new Stack<String>();
String tmp = "";
s= s.trim();
for(int i=0; i<s.length();i++){
if(s.charAt(i)!=' '){
tmp = tmp+s.charAt(i);
}else{
if(s.charAt(i+1)==' '){
continue;
}else{
stack.push(tmp);
tmp = "";
}
}
}
if(tmp!=""){
stack.push(tmp);
}
String re="";
while(!stack.empty()){
re += stack.pop()+" ";
}
return re.trim();
}
参考答案分析:
1.利用正则表达式去分解原始字符串:
2. 从后向前遍历加入结果数组当中。
代码:
public static String reverseString(String s){
String[] parts = s.trim().split("\\s+");
String out ="";
if(s.length()>0){
for(int i=parts.length-1; i>0 ; i--){
out+= parts[i]+" ";
}
out +=parts[0];
}
return out;
}
给定一个字符串由不同单词组成,返回其相反顺序,中间可能有多余字符:
例如:
Given s = "
the sky is blue",
return "
blue is sky the".
个人解法:
1.暴力,主要是对于两个单词中间存在多个空格的处理。
2. 利用栈来存储临时变量。
3.缺点,空间利用太大
代码:
public String reverseWords(String s) {
Stack<String> stack = new Stack<String>();
String tmp = "";
s= s.trim();
for(int i=0; i<s.length();i++){
if(s.charAt(i)!=' '){
tmp = tmp+s.charAt(i);
}else{
if(s.charAt(i+1)==' '){
continue;
}else{
stack.push(tmp);
tmp = "";
}
}
}
if(tmp!=""){
stack.push(tmp);
}
String re="";
while(!stack.empty()){
re += stack.pop()+" ";
}
return re.trim();
}
参考答案分析:
1.利用正则表达式去分解原始字符串:
2. 从后向前遍历加入结果数组当中。
代码:
public static String reverseString(String s){
String[] parts = s.trim().split("\\s+");
String out ="";
if(s.length()>0){
for(int i=parts.length-1; i>0 ; i--){
out+= parts[i]+" ";
}
out +=parts[0];
}
return out;
}
相关文章推荐
- HDU5025
- switch
- 重温C++之“字符类型总结区别wchar_t,char,WCHAR”
- Cocos2d-x 3.1 内存管理机制
- Cocos2d-X权威指南笔记
- CocosDeshion's android.mk 文件的理解
- cocos2dx导入到eclipse出现"C/C++ Indexer". java.lang.NullPointerException
- Cocos2d-x-3.6 用户交互原理---------如何通过JNI连接Java和C++
- POJ 1328 Radar Installation 贪心 难度:1
- 2-5-RHEL6.5搭建NFS服务器案例分析与总结(Red Hat Enterprise Linux Server6.5)@
- HDU 5358 First One(枚举)
- std::string用法总结
- C++ Virtual详解
- Java和Javascript对比
- std::thread and std::mutex
- C++中friend的使用(friend function and friend class)
- std::function与std::bind 函数指针
- Sprite 3D用法和相关特性详解(包括如何从零到一个完整工程)
- 【小熊刷题】valid palindrome
- cocos2d-x的android项目中如何加载第三方so库