151. 反转字符串中的单词 1

发布时间 2023-11-11 22:40:22作者: 追梦•少年

2023-11-11

151. 反转字符串中的单词 - 力扣(LeetCode)

思路:

         栈 利用栈  很好想,很好写

        这里是将字符部分存入list,再逆序取出,相当于栈了;可以直接利用栈,简单方便

        还有其他思路解法-》2

class Solution {
    public String reverseWords(String s) {
        //栈 利用栈  很好想,很好写
 
        String newS="";
 
        List<String>  ls=new ArrayList<>();
 
        for(int i=0;i<s.length();i++){
            char c=s.charAt(i);
            String cc=c+"";
            String temp="";
            if(cc.equals(" ")){
                continue;
            }
 
            while(i<s.length()-1 && !(cc.equals(" "))){
                temp+=cc;
                i++;
                c=s.charAt(i);
                cc=c+"";
            }
 
            if(i==s.length()-1){
                c=s.charAt(i);
                cc=c+"";
                if(!cc.equals(" ")){
                    temp+=cc;
                }
            }
 
 
            ls.add(temp);
 
        }
 
        ListIterator<String> it = ls.listIterator();
 
        while (it.hasNext()) {
            it.next();
        }
 
        while(it.hasPrevious()){
            newS+=it.previous();
            newS+=" ";
        }
        newS=newS.substring(0,newS.length()-1);
 
        return newS;
    }
}