I am wondering how to optimize my solution to the LeetCode question: 5. Longest palindromic substring:
Given a string
s
, return the longest palindromic substring ins
.
I get Time Limit exceeded on really long strings (up to 1000 characters), but on the other hand, using the same long string on my terminal gives me the correct answer instantly. Here is a string on which I get the error:
"zudfweormatjycujjirzjpyrmaxurectxrtqedmmgergwdvjmjtstdhcihacqnothgttgqfywcpgnuvwglvfiuxteopoyizgehkwuvvkqxbnufkcbodlhdmbqyghkojrgokpwdhtdrwmvdegwycecrgjvuexlguayzcammupgeskrvpthrmwqaqsdcgycdupykppiyhwzwcplivjnnvwhqkkxildtyjltklcokcrgqnnwzzeuqioyahqpuskkpbxhvzvqyhlegmoviogzwuiqahiouhnecjwysmtarjjdjqdrkljawzasriouuiqkcwwqsxifbndjmyprdozhwaoibpqrthpcjphgsfbeqrqqoqiqqdicvybzxhklehzzapbvcyleljawowluqgxxwlrymzojshlwkmzwpixgfjljkmwdtjeabgyrpbqyyykmoaqdambpkyyvukalbrzoyoufjqeftniddsfqnilxlplselqatdgjziphvrbokofvuerpsvqmzakbyzxtxvyanvjpfyvyiivqusfrsufjanmfibgrkwtiuoykiavpbqeyfsuteuxxjiyxvlvgmehycdvxdorpepmsinvmyzeqeiikajopqedyopirmhymozernxzaueljjrhcsofwyddkpnvcvzixdjknikyhzmstvbducjcoyoeoaqruuewclzqqqxzpgykrkygxnmlsrjudoaejxkipkgmcoqtxhelvsizgdwdyjwuumazxfstoaxeqqxoqezakdqjwpkrbldpcbbxexquqrznavcrprnydufsidakvrpuzgfisdxreldbqfizngtrilnbqboxwmwienlkmmiuifrvytukcqcpeqdwwucymgvyrektsnfijdcdoawbcwkkjkqwzffnuqituihjaklvthulmcjrhqcyzvekzqlxgddjoir"
Below you can find my solution to the problem where i use two functions.
- ispalindrome (boolean) to check wheather a given string is a palindrome.
- longestpalindrome(): The algorithm that uses sliding window to check wheather the string provdided is the longest palindrome.
class Solution {
public:
bool ispalindrome(string s) {
int i = 0, j = s.size() - 1;
while(i <= j){
if(s[i] != s[j]){
return false;
}
i++;
j--;
}
return true;
}
string longestPalindrome(string s) {
int window_size = s.size() - 1;
int left = 0, right = window_size;
string tmp_str = "";
while (right < s.size()) {
tmp_str.append(s.begin() + left, s.begin() + right + 1);
if (ispalindrome(tmp_str)) {
return tmp_str;
}
if((right + 1) < s.size()) {
tmp_str = "";
right++;
left++;
} else {
tmp_str = "";
window_size--;
right = window_size;
left = 0;
}
}
return s;
}
};