(LeetCode 面试经典 150 题) 151. 反转字符串中的单词(栈+字符串)
题目:151. 反转字符串中的单词
思路:栈+字符串,时间复杂度0(n)。
C++版本:
class Solution {
public:string reverseWords(string s) {stack<string> st;string tmp="";for(int i=0;i<s.size();i++){if(s[i]==' '){if(tmp!="") {st.push(tmp);tmp="";}}else{tmp.push_back(s[i]);}}if(tmp!="") {st.push(tmp);}tmp="";while(st.size()){tmp+=st.top();st.pop();if(st.size()) tmp.push_back(' ');}return tmp;}
};
JAVA版本:
class Solution {public String reverseWords(String s) {Stack<String> st=new Stack<>();String tmp="";char[] c=s.toCharArray();for(int i=0;i<c.length;i++){if(c[i]==' '){if(tmp!="") {st.add(tmp);tmp="";}}else{tmp+=c[i];}}if(tmp!="") {st.push(tmp);}tmp="";while(st.size()>0){tmp+=st.peek();st.pop();if(st.size()>0) tmp+=" ";}return tmp;}
}
Go版本:
func reverseWords(s string) string {st:=[]string{}tmp:=""for i:=0;i<len(s);i++ {if s[i]==' ' {if tmp!="" {st=append(st,tmp)tmp=""}}else{tmp+=string(s[i])}}if tmp!="" {st=append(st,tmp)}tmp=""for len(st)!=0 {tmp+=st[len(st)-1]st=st[:len(st)-1]if len(st)!=0 {tmp+=" "}}return tmp
}