Given an input string, reverse the string word by word.
For example,
Given s = " the sky is blue
",
Return " blue is sky the
".
Click to show Clarification.
Clarification:
- what constitutes a word?
A sequence of non-space characters constitutes a word.
- could the input string contain leading or trailing spaces?
yes. However, your reversed string should not contain leading or trailing spaces.
- how about multiple spaces between?
reduce them to a single space in the reversed string.
Package com.liuhao.acm.leetcode;/** * @author Liuhao * * Given A input string, reverse the string word by word. F or example, * Given s = "The Sky is Blue", return "Blue was Sky the". */public class Reversewords {public static String Reversewords (string s) {//If the input string is directly empty, return the string if (S.equals (")) {return" ";} Divide the string by the space "\\s{1,}" and the regular of one or more spaces: "\\s{1,}" string[] Strarr = S.split ("\\s{1,}"); int len = strarr.length;// After splitting the string into an empty string, return directly if (len = = 0) {return "";} Use StringBuilder more effective StringBuilder sb = new StringBuilder ("");//invert the output before splitting the string array for (int i = len-1; I >= 0; i--) {if (!strarr[i].equals (")") {Sb.append (strarr[i]); Sb.append ("");}} Sb.deletecharat (Sb.lastindexof ("")); return sb.tostring ();} public static void Main (string[] args) {System.out.println (Reversewords (""));}}
"Leetcode Brush problem Java Edition" Reverse Words in a String