Skip to content

Instantly share code, notes, and snippets.

@Chen-tao
Created January 26, 2017 08:48
Show Gist options
  • Save Chen-tao/a226575f7384e72f488506d57cdddd02 to your computer and use it in GitHub Desktop.
Save Chen-tao/a226575f7384e72f488506d57cdddd02 to your computer and use it in GitHub Desktop.
//https://leetcode.com/problems/reverse-words-in-a-string/
// O(1) space v
public void reverseWords(char[] s) {
int i=0;
for(int j=0; j<s.length; j++){
if(s[j]==' '){
reverse(s, i, j-1);
i=j+1;
}
}
reverse(s, i, s.length-1);
reverse(s, 0, s.length-1);
}
public void reverse(char[] s, int i, int j){
while(i<j){
char temp = s[i];
s[i]=s[j];
s[j]=temp;
i++;
j--;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment