Skip to content

Commit

Permalink
solution(cpp): 5. Longest Palindromic Substring
Browse files Browse the repository at this point in the history
5. Longest Palindromic Substring
- C++
  • Loading branch information
godkingjay authored Oct 29, 2023
2 parents 124665d + 6a8b13b commit d4cfdf4
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions Medium/5. Longest Palindromic String/longestPalindromic.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
class Solution {
public:
string longestPalindrome(string s) {
int n = s.length();
int st = 0;
int max_len = 1;

if(n == 1) return s;

for(int i=0; i < n-1; i++) {
int l = i, r = i;
while(l >= 0 && r < n && s[l] == s[r]) {
l--;
r++;
}
int len = r-l-1;
if(len > max_len) {
max_len = len;
st = l+1;
}
}

for(int i=0; i < n-1; i++) {
int l = i, r = i+1;
while(l >= 0 && r < n && s[l] == s[r]) {
l--;
r++;
}
int len = r-l-1;
if(len > max_len) {
max_len = len;
st = l+1;
}
}

return s.substr(st, max_len);
}
};
Binary file not shown.

0 comments on commit d4cfdf4

Please sign in to comment.