您的位置:首页 > 职场人生

[LeetCode]Reverse Words in a String 新题151

2014-03-08 13:50 344 查看
Given an input string, reverse the string word by word.

For example,

Given s = "
the sky is blue
",

return "
blue is sky the
".
这个题不难,结果我做的时候出现了TIME LIMIT EXCEED
之前是用栈做的,把每个单词push进去,pop出来,就是倒序了么,感觉算法肯定是O(n),就算testcase很长,怎么会报错呢。。

后来发现是用了String的问题,还是学得不精,大家可以搜下String和StringBuffer的区别

http://blog.csdn.net/yirentianran/article/details/2871417

这篇博客讲得挺清楚的,就是String 是final,不能继承,一旦创建出来了,e.g String s="sky"  不能更改了

那么在堆内存中就有个s ,内容是sky, 如果要s+=" is", 那么还得重新创建一个string,加上 is,最后成了 s="sky is"

这个过程其实就用了StringBuffer的append

所以在操作这样的字符串,最好还是用stringbuffer, 自己试验过了才发现stirng的操作相当耗时耗内存

public class Solution {
public String reverseWords(String s) {
Stack<String> st=new Stack<String>();
int start=0;
int end=s.length()-1;
while(start<=s.length()-1&&s.charAt(start)==' '){
start++;
}
while(end>=0&&s.charAt(end)==' '){
end--;
}
if(start>end) return "";
StringBuffer result= new StringBuffer();
while(start<=end){
StringBuffer word=new StringBuffer();
while(end>=start&&s.charAt(end)!=' '){
word.append(s.charAt(end));end--;
}
word.reverse();
if(!word.equals("")) {result.append(word+" ");}
while(end>=start&&s.charAt(end)==' ') end--;
}

return result.substring(0,result.length()-1).toString();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息