Leetcode 647. Palindromic Substrings 回文子串 解题报告
2017-08-01 20:29
393 查看
这道题,就是找出一个字符串中所有可能出现的回文子串的个数。
做法嘛,就是一个个位置的统计,使用中心向外拓展的方法:
1、每个字符自己构成回文,+1
2、中心拓展,假设当前位置i为回文的中心,那么设置left=i-1 right=i+1,比较left与right位置是否相同,相同就+1,然后各自移动一步,重复直到退出
3、中心拓展当前的回文长度是偶数的,那么就设置left=i,right=i+1,其他同2一样
这道题我用python写的,其实用java会更简洁,因为可以(++ –)
做法嘛,就是一个个位置的统计,使用中心向外拓展的方法:
1、每个字符自己构成回文,+1
2、中心拓展,假设当前位置i为回文的中心,那么设置left=i-1 right=i+1,比较left与right位置是否相同,相同就+1,然后各自移动一步,重复直到退出
3、中心拓展当前的回文长度是偶数的,那么就设置left=i,right=i+1,其他同2一样
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 exceed 1000.
这道题我用python写的,其实用java会更简洁,因为可以(++ –)
class Solution(object): def countSubstrings(self, s): """ :type s: str :rtype: int 从中心拓展出去 """ res = 0 n = len(s) for i in range(0, n): # itself res += 1 # odds left = i -1 right = i + 1 while left >= 0 and right < n and s[left] == s[right]: left -= 1 right += 1 res += 1 # evens left = i right = i + 1 while left >= 0 and right < n and s[left] == s[right]: left -= 1 right += 1 res += 1 return res
相关文章推荐
- Leetcode 115. Distinct Subsequences 计算子串 解题报告
- 广师OJ 2238 回文子串 解题报告
- leetcode解题之5. Longest Palindromic Substring Java版(最长回文子串)
- Leetcode 125. Valid Palindrome 回文验证 解题报告
- 回文子串解题报告
- [leetcode] 355. Design Twitter 解题报告
- 【LeetCode】123.Best Time to Buy and Sell Stock III(Hard)解题报告
- [leetcode] 114. Flatten Binary Tree to Linked List 解题报告
- 【LeetCode】163.Missing Ranges(Medium)(带锁题)解题报告
- [LeetCode] Largest Rectangle in Histogram 解题报告
- [LeetCode] Remove Duplicates from Sorted List 解题报告
- [LeetCode] Minimum Window Substring 解题报告
- [LeetCode] Simplify Path 解题报告
- [LeetCode]Word Break,解题报告
- [LeetCode] Validate Binary Search Tree 解题报告
- 解题报告:LeetCode The Skyline Problem(画天际线)
- LeetCode解题报告--4Sum
- [leetcode] 236. Lowest Common Ancestor of a Binary Tree 解题报告
- 【LeetCode】96. Unique Binary Search Trees 解题报告
- 【LeetCode】Palindrome Linked List 解题报告