leetcode 151 reverse word

Original question here

The input string contains spaces, and we use the space as the boundary to divide the string. split ("")

Then we traverse the split strings and stitch them together.

Finally, let's make a judgment. If the last character is a space, it should be deleted. Note here that we must first determine whether the string after splicing is an empty string

public static String reverseWords(String s) {
        if(s.length()==0) return s;
        String [] words = s.split(" ");
        StringBuilder ans = new StringBuilder();
        for(int i=words.length-1;i>0;i--){
            if(words[i].length()==0) continue;
            ans.append(words[i]);
            ans.append(" ");
        }
        if(ans.charAt(ans.length())==' '){
            ans.deleteCharAt(ans.length());
        }
        return ans.toString();


    }
View Code

 

Guess you like

Origin www.cnblogs.com/superxuezhazha/p/12675643.html