Preface
Leetcode (Address: https://oj.leetcode.com/) is an online programming site, typical questions, test cases complete, a total of 157 algorithm class questions. Afterwards, I will record some of my exercise questions. Some of my answers are self-made (original, or probably seen elsewhere) and some are from the discussion board, I will clearly mark the source.
Reverse words in a string
Given an input string, reverse the string word by word.
For example,
Given S = "the sky is blue ",
Return "Blue is sky ".
Click to show clarification.
Clarification:
- What constitutes a word?
A sequence of non-space characters constitutes a word.
- Cocould the input string contain leading or trailing spaces?
Yes. However, your reversed string shocould not contain leading or trailing spaces.
- How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
[My analysis] I used to reverse all strings and then reverse them by words, but the difficulty was how to deal with multiple spaces.
[Analysis 1-non-original] There may be multiple spaces between words. The character temp is scanned from the past and the result is returned:
1) if it is not a space, word + = temp;
2) if it is a space, append word to the front of result.
Reference: https://oj.leetcode.com/discuss/10888/my-java-solution-few-lines
/* Method 1: The second-level cache concept. Word is used to store characters. In case of space, if word is not a space, add word to the front of newstr of the string, set it to "" */public static string reversewords4 (string s) {string temp = ""; string result = ""; for (INT I = 0; I <S. length (); I ++) {char c = S. charat (I); If (C = '') {If (temp! = "" & Result! = "") {Result = temp + "" + result;} If (temp! = "" & Result = "") {result = temp;} temp = "" ;}else {temp + = C ;}} /* Last add */If (temp! = "" & Result! = "") {Result = temp + "" + result;} If (temp! = "" & Result = "") {result = temp;} return result ;}
[Analysis 2-non-original] use regular expressions to separate strings into string arrays. This requires system functions.
Reference: https://oj.leetcode.com/discuss/9142/my-accepted-java-solution
Solution 1: system functions trim () and split ()
/* Regular Expression \ s + represents any number of blank characters */public static string reversewords3 (string s) {string [] parts = S. trim (). split ("\ s +"); string out = ""; if (parts. length> 0) {for (INT I = parts. length-1; I> 0; I --) {out + = parts [I] + "";} out + = parts [0];} return out ;}
Solution 2: The default constructor of the system category separates strings by blank characters.
public String reverseWords(String s) { Scanner parts = new Scanner(s); String result = ""; while(parts.hasNext()){ result = parts.next() + " " + result; } return result.trim(); }
[Leetcode online programming record-1] string inversion by word