-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem5.cpp
More file actions
55 lines (50 loc) · 1.38 KB
/
problem5.cpp
File metadata and controls
55 lines (50 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// class Solution {
// public:
// string longestPalindrome(string s) {
// int max = 0;
// string res="";
// string final;
// BRUTE FORCE SOLUTION - O(n^3)
// for(int l=0 ; l<s.length(); l++) {
// res="";
// for(int j =l ; j<s.length(); j++ ){
// res+=s[j];
// string temp =res;
// reverse(temp.begin() , temp.end());
// if ( temp==res && max <res.length() ) {
// final = res;
// max = res.length();
// }
// }
// }
// return final;
// }
// };
//otimal solution O(n^2)
class Solution {
public:
string longestPalindrome(string s) {
int l,r;
int max = 0;
int start;
for(int i=0 ; i<s.length(); i++) {
l=i; r=i;
while (l>=0 && r<s.length() && s[l]==s[r]) {
if (r-l+1 > max ) {
start = l;
max = r-l+1;
}
l--; r++;
}
l=i; r=i+1;
while (l>=0 && r<s.length() && s[l]==s[r]) {
if (r-l+1 > max ) {
start = l;
max = r-l+1;
}
l--; r++;
}
}
return s.substr(start , max);
}
};