Skip to content

Instantly share code, notes, and snippets.

@NeoZhangTCL
Created May 31, 2017 15:13
Show Gist options
  • Save NeoZhangTCL/85c7275aa96fd4eba31f0fe606792ccc to your computer and use it in GitHub Desktop.
Save NeoZhangTCL/85c7275aa96fd4eba31f0fe606792ccc to your computer and use it in GitHub Desktop.
public class Solution {
public String reverseString(String s) {
char[] word = s.toCharArray();
for(int i=0, j=s.length()-1; i<j; i++, j--){
char temp = word[i];
word[i] = word[j];
word[j] = temp;
}
return new String(word);
}
}
public class Solution {
public String reverseString(String s) {
StringBuilder sb = new StringBuilder(s);
for(int i=0, j=s.length()-1; i<j; i++, j--){
char temp = sb.charAt(i);
sb.setCharAt(i, sb.charAt(j));
sb.setCharAt(j, temp);
}
return sb.toString();
}
}
@NeoZhangTCL
Copy link
Author

array solution is faster 2ms, stringbuilder slower 6ms, DONOT use insert and add, otherwise it is O(n^2)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment