第一題 迴文串個數
給定一個字符串,你的任務是計算這個字符串中有多少個迴文子串。
具有不同開始位置或結束位置的子串,即使是由相同的字符組成,也會被計爲是不同的子串。
示例 1:
輸入: "abc"
輸出: 3
解釋: 三個迴文子串: "a", "b", "c".
示例 2:
輸入: "aaa"
輸出: 6
說明: 6個迴文子串: "a", "a", "a", "aa", "aa", "aaa".
真的超級簡單了,原以爲很複雜,迴文串也就這樣,時間也是擊敗77%,記住思想啊,countx(i,i+1)是解決出現aa這種情況
class Solution {
public:
int count=0;
int countSubstrings(string s) {
int size=s.size();
for (int i=0;i<size;i++){
countx(s,i,i);
countx(s,i,i+1);
}
return count;
}
void countx(string s,int st,int en){
while(st>=0&&en<=s.size()-1&&s[st]==s[en]){
count++;
st--;
en++;
}
}
};
第二題 最大回文子串
給定一個字符串 s
,找到 s
中最長的迴文子串。你可以假設 s
的最大長度爲 1000。
示例 1:
輸入: "babad" 輸出: "bab" 注意: "aba" 也是一個有效答案。
思路:注意使用string.substr(a,b),第一個參數是起點,第二個參數是長度
class Solution {
public:
int max_res=0;
int stt=0,enn=0;
string longestPalindrome(string s) {
int len=s.size();
for(int i=0;i<len;i++)
{
countx(s,i,i);
countx(s,i,i+1);
}
return s.substr(stt,enn-stt+1);
}
void countx(string s,int st,int en){
while(st>=0&&en<=s.size()-1&&s[st]==s[en]){
if(max_res<=en-st+1)
{
stt=st;
enn=en;
max_res=en-st+1;
}
st--;
en++;
}
}
};