(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
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值