151.Reverse Words in a String Posted on 2017-09-13 | In LeetCode Test cases1" " // expect "" Solution 1: accepted 20msTime: O(n)Space: O(n) 123456789101112131415161718public String reverseWords(String s) { StringBuilder sb = new StringBuilder(); String temp = ""; for (int i = s.length() - 1; i >= 0; i--) { char cur = s.charAt(i); if (cur == ' ' && temp.length() != 0) { sb.append(temp + " "); temp = ""; } else if (cur == ' ') { continue; } else { temp = cur + temp; } } sb.append(temp); return sb.toString().trim();} Solution 2: accepted 12msTime: O(n)Space: O(n) 12345678public String reverseWords(String s) { String[] words = s.trim().split("\\s+"); StringBuilder sb = new StringBuilder(); for (int i = words.length - 1; i >= 0; i--) { sb.append(words[i] + " "); } return sb.deleteCharAt(sb.length() - 1).toString();}