剑指 Offer 58 - I. 翻转单词顺序

package leetcode;

import java.util.Stack;


public class offer_58_1 {
    /*
    public String reverseWords(String s) {
        //先翻转整体再翻转局部
        StringBuffer sb=new StringBuffer(s);
        s=sb.reverse().toString();
        String[] str=s.split(" ");
        s="";
        for(int i=0;i<str.length;i++) {
            if(str[i].equals("")) {
                continue;
            }
            sb=new StringBuffer(str[i]);
            str[i]=sb.reverse().toString();
            s=s+str[i];
            if(i!=str.length-1) {
                s=s+" ";
            }
        }
        return s;
    }*/
    public String reverseWords(String s) {
        String[] str=s.split(" ");
        s="";
        for(int i=str.length-1;i>=0;i--) {
            if(str[i].equals("")) {
                continue;
            }
            s=s+str[i];
            if(i!=0) {
                s=s+" ";
            }
        }
        if(s.endsWith(" ")) {
            s=s.substring(0,s.length()-1);
        }
        return s;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        offer_58_1 off=new offer_58_1();
        System.out.println(off.reverseWords(" hello world! "));
    }

}

 

posted on 2022-03-14 11:36  一仟零一夜丶  阅读(28)  评论(0)    收藏  举报