当前位置:网站首页>LeetCode:647. 回文子串
LeetCode:647. 回文子串
2022-07-30 06:14:00 【Bertil】
给你一个字符串 s ,请你统计并返回这个字符串中 回文子串 的数目。
回文字符串 是正着读和倒过来读一样的字符串。
子字符串 是字符串中的由连续字符组成的一个序列。
具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被视作不同的子串。
示例 1:
输入:s = "abc"
输出:3
解释:三个回文子串: "a", "b", "c"
示例 2:
输入:s = "aaa"
输出:6
解释:6个回文子串: "a", "a", "a", "aa", "aa", "aaa"
提示:
- 1 <= s.length <= 1000
- s 由小写英文字母组成
### 解题思路 1.首先定义一个变量count来计算回文子串的个数 2.然后使用双指针遍历出所有的子串(分别按顺序和逆序累加字符串),然后判断两个子串是否相等,若相等(即为回文子串)则count++ 3.最后返回count即可
代码
/** * @param {string} s * @return {number} */
var countSubstrings = function(s) {
let count = 0;
for (let i = 0; i < s.length; i++) {
let s1 = '', s2 = '';
for (let j = i; j < s.length; j++) {
s1 = s1 + s[j], s2 = s[j] + s2;// 分别按顺序和逆序累加字符串
if (s1 === s2) count++;
}
}
return count;
};
边栏推荐
猜你喜欢
随机推荐
Go uses the mencached cache
2020年度总结——品曾经,明得失,展未来
Electron之初出茅庐——搭建环境并运行第一个程序
k8s 部署mysql8(PV和PVC 版本)
五号黯区靶场 mysql 注入之limit注入记录
Oracle查看表空间使用率及爆满解决方案
No, the Log4j vulnerability hasn't been fully fixed yet?
Map file analysis in Keil software
golang: Gorm配置Mysql多数据源
MySQL master-slave replication configuration construction, one step in place
go : 使用gorm创建数据库记录
【MySQL】MySQL中如何实现分页操作
包含min函数的栈(js)
【雷达目标检测】恒定阈值法和恒虚警(CFAR)法及代码实现
万能js时间日期格式转换
MYSQL下载及安装完整教程
How does Redis prevent oversold and inventory deduction operations?
Universal js time date format conversion
IDEA 中CheckStyle安装及使用
02 多线程与高并发 - synchronized 解析









