Skip to content

Commit 59d5cc2

Browse files
created java file
1 parent 11a2f4c commit 59d5cc2

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Java/reverse-words-in-a-string.java

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* Reverse Words in a String
3+
* Medium
4+
*
5+
* Given an input string, reverse the string word by word
6+
7+
Example 1:
8+
9+
Input: "the sky is blue"
10+
Output: "blue is sky the"
11+
12+
Example 2:
13+
14+
Input: " hello world! "
15+
Output: "world! hello"
16+
Explanation: Your reversed string should not contain leading or trailing spaces.
17+
*
18+
* Runtime: 7 ms
19+
* Memory Usage: 41.8 MB
20+
*
21+
*/
22+
class Solution {
23+
public String reverseWords(String s) {
24+
s = s.trim();
25+
26+
String [] strArr = s.split(" ");
27+
28+
String ans = "";
29+
30+
for (int i=strArr.length-1; i>=0; i--) {
31+
if (strArr[i].isEmpty()){
32+
continue;
33+
}
34+
ans += strArr[i].trim() + " ";
35+
}
36+
37+
return ans.trim();
38+
}
39+
}

0 commit comments

Comments
 (0)