Created
May 31, 2017 15:13
-
-
Save NeoZhangTCL/85c7275aa96fd4eba31f0fe606792ccc to your computer and use it in GitHub Desktop.
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
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); | |
} | |
} |
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
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
array solution is faster 2ms, stringbuilder slower 6ms, DONOT use insert and add, otherwise it is O(n^2)