We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 11a2f4c commit 59d5cc2Copy full SHA for 59d5cc2
Java/reverse-words-in-a-string.java
@@ -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