大致意思就是typed对应位置上的相同字符数要大于等于name对应位置上的字符 思路:双指针遍历,每次都找出对应位置上字符的个数,再比较即可,注意不要忘了typed字符串过长的问题;
bool isLongPressedName(string name, string typed) { //双指针遍历两个字符串 int p1 = 0, p2 = 0; int len1 = name.size(), len2 = typed.size(); if (len1 == 0 && len2 == 0) { return true; } if (len1 == 0 && len2 > 0) { return false; } //只要name没被遍历完,就继续执行 while (p1 < len1) { char c = name[p1]; int count1 = 0; while (p1 < len1 && name[p1] == c) { p1++; count1++; } int count2 = 0; while (p2 < len2 && typed[p2] == c) { p2++; count2++; } if (count2 < count1)//如果typed中没有该字符或者该字符个数比name中对应位置的少,直接return false { return false; } } if (p2 != len2)//如果typed后面还有多余字符 { return false; } return true; }