LeetCode每日一题-长按键入

it2024-01-30  65

长按键入

你的朋友正在使用键盘输入他的名字 name。偶尔,在键入字符 c 时,按键可能会被长按,而字符可能被输入 1 次或多次。 你将会检查键盘输入的字符 typed。如果它对应的可能是你的朋友的名字(其中一些字符可能被长按),那么就返回 True。

class Solution { public: bool isLongPressedName(string name, string typed) { //1、鲁棒性检查 if(!name.size() && !typed.size()) { return true; } else if(name.size() && !typed.size()) { return false; } else if(!name.size() && typed.size()) { return false; } //2、遍历 + 计数 + 对比 int i = 0, j = 0; while(i < name.size() && j < typed.size()) { if(name[i] != typed[j]) { //如果第一个字符不相等 - 直接返回false; return false; } else { //第一个字符相等 int count1 = 1, count2 = 1; //count1存储name字符串的计数, count2存储typed字符串计数 while(i + 1 < name.size() && name[i] == name[i+1]) { //相等 count1++; i++; } while(j + 1 < typed.size() && typed[j] == typed[j+1]) { count2++; j++; } i++; j++; //如果count1 <= count2 正确, 相反错误返回false if(count1 > count2) { return false; } } } if(i == name.size() && j == typed.size()) { return true; } return false; } };
最新回复(0)