647. Palindromic Substrings(python+cpp)
阿新 • • 發佈:2018-11-21
題目:
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
Example 1:Input: "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: "aaa" Output: 6 Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
Note:
The input string length won’t exceed1000
.
解釋:
查詢一個字串中有多少個是迴文的子字串。
reuse之前的結果~
從中間往兩邊走(使用中心向外拓展的方法)
假設當前位置i為迴文的中心,那麼迴文中心有兩種情況,即迴文長度是奇數的情況或者回文長度是偶數的情況,
如果迴文是奇數,left=i-1,right=i+1
如果迴文是偶數,left=i,right=i+1
i的取值範圍是0~n-1
python程式碼:
class Solution(object):
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
len_s=len(s)
result=0
for i in xrange(len_s):
result+=1
#迴文長度是奇數的情況:
left=i-1
right=i+1
while left>=0 and right<len_s and s[left]==s[right]:
result+=1
left-=1
right+=1
#迴文長度是偶數的情況
left=i
right=i+1
while left>=0 and right<len_s and s[left]==s[right]:
result+=1
left-=1
right+=1
return result
c++程式碼:
class Solution {
public:
int countSubstrings(string s) {
int len_s=s.size();
int result=0;
for(int i=0;i<len_s;i++)
{
result++;
int left=i-1,right=i+1;
while(left>=0 && right<len_s && s[left]==s[right])
{
result++;
left--;
right++;
}
left=i;
right=i+1;
while(left>=0 && right<len_s && s[left]==s[right])
{
result++;
left--;
right++;
}
}
return result;
}
};
總結: