-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem_151.java
More file actions
26 lines (25 loc) · 818 Bytes
/
Copy pathproblem_151.java
File metadata and controls
26 lines (25 loc) · 818 Bytes
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
/*151. Reverse Words in a String
Given an input string s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space. */
class Solution {
public String reverseWords(String s) {
s = s.strip().replaceAll("\\s+", " ");
String rev ="", rev_sen="";
int i = s.length()-1;
while(i>-1){
while(i>-1 && s.charAt(i) != ' ' ){
rev = String.valueOf(s.charAt(i--)) + rev;
}
if(i>-1){
rev_sen += rev + " ";
}
else{
rev_sen += rev;
}
rev = "";
i--;
}
return rev_sen;
}
}