|
1 | 1 | ## Algorithm
|
2 | 2 |
|
| 3 | +[151. Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) |
| 4 | + |
3 | 5 | ### Description
|
4 | 6 |
|
5 |
| -### Solution |
| 7 | +Given an input string s, reverse the order of the words. |
| 8 | + |
| 9 | +A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. |
| 10 | + |
| 11 | +Return a string of the words in reverse order concatenated by a single space. |
| 12 | + |
| 13 | +Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces. |
| 14 | + |
| 15 | + |
| 16 | +Example 1: |
| 17 | + |
| 18 | +``` |
| 19 | +Input: s = "the sky is blue" |
| 20 | +Output: "blue is sky the" |
| 21 | +``` |
| 22 | + |
| 23 | +Example 2: |
| 24 | + |
| 25 | +``` |
| 26 | +Input: s = " hello world " |
| 27 | +Output: "world hello" |
| 28 | +Explanation: Your reversed string should not contain leading or trailing spaces. |
| 29 | +``` |
| 30 | + |
| 31 | +Example 3: |
6 | 32 |
|
7 |
| -```java |
| 33 | +``` |
| 34 | +Input: s = "a good example" |
| 35 | +Output: "example good a" |
| 36 | +Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string. |
| 37 | +``` |
| 38 | + |
| 39 | +Example 4: |
| 40 | + |
| 41 | +``` |
| 42 | +Input: s = " Bob Loves Alice " |
| 43 | +Output: "Alice Loves Bob" |
| 44 | +``` |
| 45 | + |
| 46 | +Example 5: |
| 47 | + |
| 48 | +``` |
| 49 | +Input: s = "Alice does not even like bob" |
| 50 | +Output: "bob like even not does Alice" |
| 51 | +``` |
| 52 | + |
| 53 | +Constraints: |
| 54 | + |
| 55 | +- 1 <= s.length <= 104 |
| 56 | +- s contains English letters (upper-case and lower-case), digits, and spaces ' '. |
| 57 | +- There is at least one word in s. |
| 58 | + |
| 59 | +Follow-up: If the string data type is mutable in your language, can you solve it in-place with O(1) extra space? |
| 60 | + |
| 61 | +### Solution |
8 | 62 |
|
| 63 | +```java |
| 64 | +class Solution { |
| 65 | + public String reverseWords(String s) { |
| 66 | + Stack<String> stack = new Stack<>(); |
| 67 | + String temp = ""; |
| 68 | + for(int i=0;i<s.length();i++){ |
| 69 | + if(s.charAt(i)==' '&&temp.length()!=0){ |
| 70 | + stack.push(temp); |
| 71 | + temp = ""; |
| 72 | + }else if(s.charAt(i)!=' '){ |
| 73 | + temp += s.charAt(i); |
| 74 | + } |
| 75 | + if(i==s.length()-1){ |
| 76 | + stack.push(temp.trim()); |
| 77 | + } |
| 78 | + } |
| 79 | + String result = ""; |
| 80 | + while(!stack.isEmpty()){ |
| 81 | + result += stack.pop(); |
| 82 | + result += " "; |
| 83 | + } |
| 84 | + return result.strip(); |
| 85 | + } |
| 86 | +} |
9 | 87 | ```
|
10 | 88 |
|
11 | 89 | ### Discuss
|
|
0 commit comments