Skip to content

Commit

Permalink
add solutions for Reverse-Words-in-a-String
Browse files Browse the repository at this point in the history
  • Loading branch information
xcv58 committed Feb 10, 2015
1 parent 610acf9 commit 983bd5a
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 0 deletions.
8 changes: 8 additions & 0 deletions Reverse-Words-in-a-String-II/Solution.cpp
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
#include <string>

using namespace std;

class Solution {
public:
void reverseWords(string &s) {
Expand All @@ -8,3 +12,7 @@ class Solution {
reverse(s.begin(), s.end());
}
};

int main(int argc, char *argv[]) {
return 0;
}
32 changes: 32 additions & 0 deletions Reverse-Words-in-a-String/Solution.cpp
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;
}
11 changes: 11 additions & 0 deletions Reverse-Words-in-a-String/Solution.java
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();
}
}
5 changes: 5 additions & 0 deletions Reverse-Words-in-a-String/Solution.py
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])

0 comments on commit 983bd5a

Please sign in to comment.