题目地址:
https://leetcode.com/problems/long-pressed-name/
给定两个字符串 s s s和 t t t,判断 t t t是否可能因为是 s s s中某些字符多打了几次而产生。
代码如下:
public class Solution {
public boolean isLongPressedName(String name, String typed) {
for (int i = 0, j = 0; i < name.length() || j < typed.length(); i++, j++) {
if (i == name.length() || j == typed.length()) {
return false;
}
if (name.charAt(i) != typed.charAt(j)) {
return false;
}
int ii = i;
while (ii < name.length() && name.charAt(ii) == name.charAt(i)) {
ii++;
}
int jj = j;
while (jj < typed.length() && typed.charAt(jj) == typed.charAt(j)) {
jj++;
}
if (ii - i > jj - j) {
return false;
}
i = ii - 1;
j = jj - 1;
}
return true;
}
}
时间复杂度 O ( l s + l t ) O(l_s+l_t) O(ls+lt),空间 O ( 1 ) O(1) O(1)。