forked from xcv58/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add solutions for Reverse-Words-in-a-String
- Loading branch information
Showing
4 changed files
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
#include <string> | ||
|
||
using namespace std; | ||
|
||
class Solution { | ||
public: | ||
void reverseWords(string &s) { | ||
int j = 0, len = s.length(); | ||
for (int i = 0, wordStart = 0; i < len; ) { | ||
for (; i < len && s[i] == ' '; i++); | ||
if (i == len) { break; } | ||
if (j > 0) { s[j++] = ' '; } | ||
wordStart = j; | ||
for (; i < len && s[i] != ' '; s[j++] = s[i++]); | ||
reverseWords(s, wordStart, j - 1); | ||
} | ||
s.resize(j); | ||
reverseWords(s, 0, j - 1); | ||
} | ||
|
||
void reverseWords(string &s, int i, int j) { | ||
for (; i < j; i++, j--) { | ||
char c = s[i]; | ||
s[i] = s[j]; | ||
s[j] = c; | ||
} | ||
} | ||
}; | ||
|
||
int main(int argc, char *argv[]) { | ||
return 0; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
public class Solution { | ||
public String reverseWords(String s) { | ||
String[] tokens = s.split("\\s+"); | ||
StringBuilder sb = new StringBuilder(); | ||
for (int i = tokens.length - 1; i >= 0; i--) { | ||
sb.append(tokens[i]); | ||
sb.append(' '); | ||
} | ||
return sb.toString().trim(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
class Solution: | ||
# @param s, a string | ||
# @return a string | ||
def reverseWords(self, s): | ||
return " ".join(s.split()[::-1]) |