本专栏记录以后刷题碰到的有关双指针的题目。
125. 验证回文串
题目链接:125. 验证回文串
这是一个简单题目,但条件判断自己写的时候写的过于繁杂。后面参考别人写的代码,首先先将字符串s利用s.toLowerCase()将其中的大写字母全部转换为小写字母后在进行操作。代码简化很多。
代码如下:
class Solution {
public boolean isPalindrome(String s) {
int slow = 0, fast = s.length() - 1;
char[] arrCh = s.toLowerCase().toCharArray();
// System.out.println(Arrays.toString(arrCh));
while(slow < fast){
while(slow < fast && !((arrCh[slow] >= 'a' && arrCh[slow] <= 'z') || (arrCh[slow] >= '0' && arrCh[slow] <= '9'))) ++slow;
while(slow < fast && !((arrCh[fast] >= 'a' && arrCh[fast] <= 'z') || (arrCh[fast] >= '0' && arrCh[fast] <= '9'))) --fast;
if(arrCh[slow] != arrCh[fast]) return false;
++slow;
--fast;
}
return true;
}
}
1759. 统计同质子字符串的数目
题目链接:1759. 统计同质子字符串的数目
本题关键在于同质字符串的计算的理解,最终能够得出结论,对于给定字符串aaaa,它的同质字符串个数为 4 + 3 + 2 + 1,也就是等差数列的和 n * (n + 1) / 2。如果能够推导到这一步,那这一题已经解决了。
最终代码:
class Solution {
private static final int MOD = (int) 1e9 + 7;
public int countHomogenous(String s) {
int n = s.length();
long ans = 0;
for (int i = 0, j = 0; j <= n; j++) {
if(j == n || s.charAt(j) != s.charAt(i)){
int diff = j - i;
ans += (long) diff * (diff + 1) / 2;
ans %= MOD;
i = j;
}
}
return (int) ans;
}
}