当前位置:网站首页>Sword finger offer II 020 Number of palindrome substrings
Sword finger offer II 020 Number of palindrome substrings
2022-06-10 00:50:00 【Small white yards fly up】
Summary
It's still a double pointer , But this time the double pointer moves to both sides at the center of the substring .
subject
Given a string s , Please calculate how many palindrome substrings there are in this string .
A substring with different start or end positions , Even if it's made up of the same characters , It's also seen as a different substring .

Ideas
This time you need to enumerate all the substrings , To determine whether it is a palindrome substring .
In the past, double pointers started from the leftmost side , The right pointer moves to determine the range of the substring . This time we focus on one character , The double pointer starts with the center character , Move to both sides . Of course , Palindrome string length has odd number and even number , So there is one or two cases at our starting point .
solution
Code
public int countSubstrings(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
count += palindromeCount(s, i, i);
count += palindromeCount(s, i, i + 1);
}
return count;
}
public int palindromeCount(String s, int left, int right) {
int count = 0;
while (left >= 0 && right < s.length()) {
if (s.charAt(left) == s.charAt(right)) {
count++;
left--;
right++;
} else {
break;
}
}
return count;
}
边栏推荐
- 试题 历届真题 回文日期【第十一届】【省赛】【B组】
- go配置文件管理-viper
- gurobi解的状态及其属性获取
- How to optimize slow queries? (actual combat slow query)
- 【无标题】
- Cloud Mining & cloud mining chain: from order collaboration to procurement supply chain, make procurement supply chain interconnected
- Solution to C language problem of adding two numbers by force deduction
- 剑指 Offer II 010. 和为 k 的子数组
- What is the WPS merge cell shortcut
- js 邏輯空分配雙問號語法 、雙豎杠語法 與 可選鏈語法
猜你喜欢

OSPF实验
Analysis on the scores of previous real questions [11th] [provincial competition] [group B]

Minimum toll

Pycharm 2022 permanently activated version download, valid for personal test

剑指 Offer II 010. 和为 k 的子数组
力扣 自除数 C语言 题解

Go zero micro Service Practice Series (II. Service splitting)
试题 历届真题 完全二叉树的权值【第十届】【省赛】【B组】

Collection backup | summary of some common problems about oauth2

BGP协议实验
随机推荐
OSPF first experiment
Apply the latest ad and Txk patches
Work sharing of 2018 virtual instrument competition - reconfigurable snake shaped robot based on LabVIEW, baidu map, STM32 single chip microcomputer, etc
试题 历届真题 成绩分析【第十一届】【省赛】【B组】
[typecho] find articles written in non markdown scripting languages
OSPF实验
力扣 旋转字符串 C语言 题解
typora 基本使用和更换typora的主题样式
BGP协议实验
Pycharm 2022 permanently activated version download, valid for personal test
MySQL execution plan
Rhcsa day 1
力扣 自除数 C语言 题解
力扣 两数相加 C语言 题解
试题 历届真题 回文日期【第十一届】【省赛】【B组】
C language solution of the longest substring of Li Kou without repeated characters
Application of DFS and BFS in binary tree
Rip experiment
最低通行费
力扣 无重复字符的最长子串 C语言 题解