leetcode 925. 长按键入

it2024-03-13  59

你的朋友正在使用键盘输入他的名字 name。偶尔,在键入字符 c 时,按键可能会被长按,而字符可能被输入 1 次或多次。

你将会检查键盘输入的字符 typed。如果它对应的可能是你的朋友的名字(其中一些字符可能被长按),那么就返回 True。

示例 1:

输入:name = “alex”, typed = “aaleex” 输出:true 解释:‘alex’ 中的 ‘a’ 和 ‘e’ 被长按。

代码

class Solution { public boolean isLongPressedName(String name, String typed) { List<Integer> s1=new ArrayList<>(),s2=new ArrayList<>(); int cur=0; for(int i=0;i<name.length();i++)//统计两个字符串字母的顺序和次数 { int c=1; while (i+1<name.length()&&name.charAt(i)==name.charAt(i+1)) { c++; i++; } s1.add((int) name.charAt(i)); s1.add(c); } for(int i=0;i<typed.length();i++) { int c=1; while (i+1<typed.length()&&typed.charAt(i)==typed.charAt(i+1)) { c++; i++; } s2.add((int) typed.charAt(i)); s2.add(c); } if(s1.size()==s2.size()) { for (int i=0;i<s1.size();i+=2)//比较两个字符串字母的顺序和次数 { if(s1.get(i)!=s2.get(i)||s1.get(i+1)>s2.get(i+1)) return false; } return true; } else return false; } }
最新回复(0)