Skip to content

Commit 8ecc718

Browse files
ReverseWordsInAString : Accepted
1 parent 04e002e commit 8ecc718

2 files changed

Lines changed: 50 additions & 0 deletions

File tree

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,7 @@ My accepted leetcode solutions to some of the common interview problems.
145145

146146
- [First Unique Character In a String](problems/src/string/FirstUniqueCharacterInAString.java) (Easy)
147147
- [Repeated Substring Pattern](problems/src/string/RepeatedSubstringPattern.java) (Easy)
148+
- [Reverse Words In a String](problems/src/string/ReverseWordsInAString.java) (Medium)
148149
- [ReverseWords II](problems/src/string/ReverseWordsII.java) (Medium)
149150
- [String to Integer](problems/src/string/StringToInteger.java) (Medium)
150151
- [Text Justification](problems/src/string/TextJustification.java) (Hard)
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package string;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
import java.util.StringTokenizer;
6+
7+
/**
8+
* Created by gouthamvidyapradhan on 04/07/2017.
9+
* Given an input string, reverse the string word by word.
10+
11+
For example,
12+
Given s = "the sky is blue",
13+
return "blue is sky the".
14+
15+
Clarification:
16+
What constitutes a word?
17+
A sequence of non-space characters constitutes a word.
18+
Could the input string contain leading or trailing spaces?
19+
Yes. However, your reversed string should not contain leading or trailing spaces.
20+
How about multiple spaces between two words?
21+
Reduce them to a single space in the reversed string.
22+
*/
23+
public class ReverseWordsInAString {
24+
public static void main(String[] args) throws Exception{
25+
System.out.println(new ReverseWordsInAString().reverseWords(" the sky is blue"));
26+
}
27+
28+
public String reverseWords(String s) {
29+
if(s == null || s.isEmpty()) return "";
30+
StringBuilder sb = new StringBuilder(s.trim());
31+
String reverse = sb.reverse().toString();
32+
StringTokenizer st = new StringTokenizer(reverse, " ");
33+
List<String> list = new ArrayList<>();
34+
while(st.hasMoreTokens()){
35+
list.add(st.nextToken());
36+
}
37+
for(int i = 0, l = list.size(); i < l; i ++){
38+
String str = list.get(i);
39+
String newStr = new StringBuilder(str).reverse().toString();
40+
list.set(i, newStr);
41+
}
42+
StringBuilder result = new StringBuilder();
43+
for(String str : list){
44+
result.append(str).append(" ");
45+
}
46+
return result.toString().trim();
47+
}
48+
49+
}

0 commit comments

Comments
 (0)