-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy path151_Reverse_Words_in_String
More file actions
65 lines (54 loc) · 1.35 KB
/
151_Reverse_Words_in_String
File metadata and controls
65 lines (54 loc) · 1.35 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
Leetcode 151: Reverse Words in a String
Detailed video explanation link: https://youtu.be/vhnRAaJybpA
C++:
----
string reverseWords(string s) {
string result;
int i = 0;
int n = s.length();
while(i < n){
while(i < n && s[i] == ' ') i++;
if(i >= n) break;
int j = i + 1;
while(j < n && s[j] != ' ') j++;
string sub = s.substr(i, j-i);
if(result.length() == 0) result = sub;
else result = sub + " " + result;
i = j+1;
}
return result;
}
Java:
----
public String reverseWords(String s) {
String result = new String();
int i = 0;
int n = s.length();
while(i < n){
while(i < n && s.charAt(i) == ' ') i++;
if(i >= n) break;
int j = i + 1;
while(j < n && s.charAt(j) != ' ') j++;
String sub = s.substring(i, j);
if(result.length() == 0) result = sub;
else result = sub + " " + result;
i = j+1;
}
return result;
}
Python3:
-------
def reverseWords(self, s: str) -> str:
result = ""
i = 0
n = len(s)
while i < n:
while i < n and s[i] == ' ': i += 1
if i >= n: break
j = i + 1
while j < n and s[j] != ' ': j += 1
sub = s[i:j]
if len(result) == 0: result = sub
else: result = sub + " " + result
i = j+1
return result