Please be brutal, and judge my code as if it was written at a top 3 tech company, straight out of college. (The method signature, and input parameter is given by the problem, so don't worry about that)
Worst case complexity: \$ O \left( n^2 \right) \$
Space complexity: \$ O \left( n \right) \$
Time it took me to solve this:
6 minutes (I got it right the first shot, and passed all the test cases)
Problem:
Given a string
S
, find the longest palindromic substring inS
. You may assume that the maximum length ofS
is 1000, and there exists one unique longest palindromic substring.
public String longestPalindrome(String s) {
String longestPalindrome = "";
for(int i = 0; i < s.length(); i++){
for(int j = s.length()-1; j >= 0 && j != i; j--){
if(isPalindrome(s.substring(i,j+1))){
if(s.substring(i, j+1).length()>longestPalindrome.length()){
longestPalindrome = s.substring(i, j+1);
return longestPalindrome;
}
}
}
}
return longestPalindrome;
}
public boolean isPalindrome(String s){
int end = s.length()-1;
for(int i=0; i<s.length()/2; i++){
if(s.charAt(i)!=s.charAt(end)){
return false;
}
end--;
}
return true;
}