Last active
September 14, 2017 20:57
-
-
Save cixuuz/f2e7235f8e85ffb4194595974a424b84 to your computer and use it in GitHub Desktop.
[214. Shortest Palindrome] #leetcode
This file contains hidden or 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
class Solution { | |
// O(n^2) O(n) | |
public String shortestPalindrome(String s) { | |
int n = s.length(); | |
String rev = new StringBuilder(s).reverse().toString(); | |
int j = 0; | |
for (int i = 0; i < n; i++) { | |
if (s.substring(0, n-i).equals(rev.substring(i))) | |
return rev.substring(0, i) + s; | |
} | |
return ""; | |
} | |
} | |
class Solution { | |
public String shortestPalindrome(String s) { | |
int n = s.length(); | |
int i = 0; | |
for (int j = n-1; j >= 0; j--) { | |
if (s.charAt(i) == s.charAt(j)) i++; | |
} | |
if (i == n) return s; | |
String rev = new StringBuilder(s.substring(i)).reverse().toString(); | |
return rev + shortestPalindrome(s.substring(0, i)) + s.substring(i); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment