題目:
給定一個字串 s,找到 s 中最長的回文子串,你可以假設 s 的最大長度為 1000,
輸入例子1:
“cbbd”
輸出例子1:
“bb”
說明:
兩層回圈列舉所有字串,若字串首尾相等,則判斷是否為回文串,并且每次保存一個串,當遇到比它長的串再賦值給他,回傳這個串即可,
代碼:
class Solution {
public:
/**
* 代碼中的類名、方法名、引數名已經指定,請勿修改,直接回傳方法規定的值即可
*
* @param s string字串
* @return string字串
*/
string longestPalindrome(string s) {
string temp="";
int n=s.length();
for(int i=0;i<n;i++){
for(int j=n-1;j>i;j--){
if(s[i]==s[j]){
int si=i;
int sj=j;
while(si!=sj&&s[si]==s[sj]&&si<sj){
si++;
sj--;
}
if(si>=sj){
string str="";
for(int k=i;k<=j;k++){
str+=s[k];
}
if(str.length()>temp.length()){
temp=str;
}
}
}
}
}
return temp;
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/258774.html
標籤:其他
