Palindromic Substrings
来源:互联网 发布:李宁淘宝旗舰店 编辑:程序博客网 时间:2024/06/05 08:53
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: 3Explanation: Three palindromic strings: "a", "b", "c".Example 2:Input: "aaa"Output: 6Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".Note:The input string length won't exceed 1000.
题解:大意就是找一个字符串中所有回文子串的个数。这里用动态规划,状态定义dp[i][j]表示字符串s[i]到s[j]的子串是否为回文,dp[i][j]=dp[i+1][j-1]&&s[i]==s[j] 从状态转移方程来开,只需要我们从下往上,从左往右遍历即可。
代码:
public static int countSubstrings(String s) { if (s == null || s.length() <2) return s.length()==1? 1: 0; int n = s.length(); boolean[][] dp = new boolean[n][n]; for (int i = 0; i < n;i++) { dp[i][0] = true; dp[n-1][i] =true; } int count = 2; //字符串头尾两个单字符回文,即对角线上已经被初始化的两个 for (int i = n - 2; i >= 0; i--) for (int j = 1; j < n; j++) { if (i > j) dp[i][j] = true; else { dp[i][j] = dp[i + 1][j - 1] && (s.charAt(i) == s.charAt(j)); count += dp[i][j] == true ? 1 : 0; } } return count; }
回文另一种解法:找中心点,然后往两边扩展判断是否相等,是否为回文。通过遍历以i为中心(奇数)或i和i+1(偶数),回文长度为奇数和偶数,遍历所有可能的中心点,查找回文的个数
int count = 0; public int better_countSubstrings(String s) { if (s == null || s.length() == 0) return 0; for (int i = 0; i < s.length(); i++) { // i is the mid point extendPalindrome(s, i, i); // odd length; extendPalindrome(s, i, i + 1); // even length } return count; } private void extendPalindrome(String s, int left, int right) { while (left >=0 && right < s.length() && s.charAt(left) == s.charAt(right)) { count++; left--; right++; } }
阅读全文
0 0
- Palindromic Substrings
- Palindromic Substrings
- Palindromic Substrings
- Palindromic Substrings
- Palindromic Substrings
- 647. Palindromic Substrings
- 647. Palindromic Substrings
- [leetcode]647. Palindromic Substrings
- leetcode 647. Palindromic Substrings
- [LeetCode]647. Palindromic Substrings
- leetcode 647. Palindromic Substrings
- [LeetCode] 647. Palindromic Substrings
- 647. Palindromic Substrings
- 【LeetCode】647. Palindromic Substrings
- 647. Palindromic Substrings
- 647. Palindromic Substrings
- Leetcode 647. Palindromic Substrings
- 647. Palindromic Substrings
- java队列BlockingQueue和ConcurrentLinkedQueue多线程并发、以及CountDownLatch与CyclicBarrier的使用
- 九、Spring Cloud系列:实战经验总结
- 【观察】推进西藏信息化建设 联想为西藏打上更深“智慧”烙印
- kafka_2.11-1.0.0单机安装
- Linux c语言程序运行时动态加载库函数
- Palindromic Substrings
- 异常类
- Our 6 Must Reads for First-Time Managers to Hit the Ground Running
- iOS加速计和陀螺仪
- linq <一>
- 高斯、柯西、拉格朗日都还在的话,他们应该最喜欢这个公众号
- 汇总:2017 年 IT 界最严重的裁员事件
- angular4环境搭建及配置
- ORACLE_IMPDP_EXPDP生产环境数据泵的使用