|
| 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