-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverse Words in a String
51 lines (38 loc) · 1.19 KB
/
Reverse Words in a String
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//https://oj.leetcode.com/problems/reverse-words-in-a-string/
/*Reverse Words in a String Total Accepted: 21883 Total Submissions: 157273 My Submissions
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
click to show clarification.
*/
import java.util.Stack;
public class Solution {
public String reverseWords(String s) {
//ArrayList<String> AL=new ArrayList<String>();
StringBuilder sb=new StringBuilder();
Stack<Character> sk = new Stack<Character>();
s.trim();
for(int i=s.length()-1;i>=0;i--)
{
if(s.charAt(i)==' ')
{
while(!sk.isEmpty())
{
sb=sb.append(sk.pop());
}
if(sb.length()>0&&sb.charAt(sb.length()-1)!=' ')
{
sb.append(' ');
}
continue;
}
sk.push(s.charAt(i));
}
while(!sk.isEmpty())
{
sb=sb.append(sk.pop());
}
return sb.toString().trim();
}
}