日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

647. Palindromic Substrings

發布時間:2025/3/18 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 647. Palindromic Substrings 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目描述:

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".

解題思路:

本體主要是考察s中每個子字符串是否是回文字符串,有兩種方法:

1.是確定子字符串的首尾,判斷是否為回文字符串。

2.以每個字符為中心,向兩端延伸判斷是否相等,相等時回文字符串個數加一,不相等時終止內層循環。

相比較而言,第二種方法效率更高,可以更快終止遍歷。

代碼:

1 class Solution { 2 public: 3 int countSubstrings(string s) { 4 int ret = s.size(); 5 int j; 6 for (int i = 0; i < s.size(); i++){ 7 for (int j = i + 1; j < s.size(); ++j) { 8 if (s[i] != s[j]) 9 continue; 10 else 11 if (check(s, i, j)) 12 ret++; 13 } 14 } 15 return ret; 16 } 17 bool check(const string& s, int left, int right) { 18 int i = left; 19 int j = right; 20 for(;i <= j; i++, j--) { 21 if (s[i] != s[j]) 22 return false; 23 } 24 return true; 25 } 26 }; View Code 1 class Solution { 2 public: 3 int countSubstrings(string s) { 4 int ret = 0; 5 for (int i = 0; i < s.size(); i++) { 6 ret += check(s, i, i); 7 ret += check(s, i, i+1); 8 } 9 return ret; 10 } 11 int check(const string& s, int left, int right) { 12 int num = 0; 13 while (left>=0 && right<s.size() && s[left--]==s[right++]) 14 num++; 15 return num; 16 } 17 }; View Code

?

class Solution {public:? ? int countSubstrings(string s) {? ? ? ? int ret = 0;? ? ? ? for (int i = 0; i < s.size(); i++) {? ? ? ? ? ? ret += check(s, i, i);? ? ? ? ? ? ret += check(s, i, i+1);? ? ? ? }? ? ? ? return ret;? ? }? ? int check(const string& s, int left, int right) {? ? ? ? int num = 0;? ? ? ? while (left>=0 && right<s.size() && s[left--]==s[right++])? ? ? ? ? ? num++;? ? ? ? return num;? ? }};

轉載于:https://www.cnblogs.com/gsz-/p/9538491.html

與50位技術專家面對面20年技術見證,附贈技術全景圖

總結

以上是生活随笔為你收集整理的647. Palindromic Substrings的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。