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

 

Note:

  1. The input string length won't exceed 1000.

 

翻譯:

給定一個字符串,你的任務是計算在字符串中有多少迴文的子字符串。

由相同字符組成的帶有不同起始下標和終止下標的子字符串都算作不同的子字符串。

例子 1:

輸入: "abc"
輸出: 3
解釋: 3個迴文字符串: "a", "b", "c".

例子 2:

輸入: "aaa"
輸出: 6
解釋: 6個迴文字符串: "a", "a", "a", "aa", "aa", "aaa".

注意:

  1. 輸入的字符串長度不超過1000。

 

思路:

從每一個字符開始判斷,分別將它作爲迴文字符的中間字符來判斷它左右兩邊的字符是否相等,由此來判斷迴文子字符,同時,注意迴文字符串分爲奇數和偶數兩種形式。參見http://www.cnblogs.com/grandyang/p/7404777.html

 

C++代碼(Visual Studio 2017):

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

class Solution {
public:
	void count(string s, int i, int j, int& res) {
		while (i >= 0 && j < s.size() && s[i] == s[j]){
			i--; j++; res++;
		}
	}

	int countSubstrings(string s) {
		if (s.empty())
			return 0;
		int res=0;
		for (int i = 0; i < s.size(); i++) {
			count(s, i, i, res);
			count(s, i, i + 1, res);
		}
		return res;
	}
};

int main()
{
	Solution s;
	string str = "aaa";
	int result = s.countSubstrings(str);
	cout << result << endl;
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章