LeetCode925.长按键入(Java+循环)

你的朋友正在使用键盘输入他的名字 name。偶尔,在键入字符 c 时,按键可能会被长按,而字符可能被输入 1 次或多次。
你将会检查键盘输入的字符 typed。如果它对应的可能是你的朋友的名字(其中一些字符可能被长按),那么就返回 True。
示例一:
输入:name = “alex”, typed = “aaleex”
输出:true
解释:‘alex’ 中的 ‘a’ 和 ‘e’ 被长按。
示例 2:
输入:name = “saeed”, typed = “ssaaedd”
输出:false
解释:‘e’ 一定需要被键入两次,但在 typed 的输出中不是这样。

题目分析

typed字符串可能是name中的某字符输入多个而形成的。
1.如果typed字符串里面存在的字符,在name里面没有,则说明为false。
2.typed跟name内容一致、长度相等,说明true。
我们可以统计name中每个字符连续出现的次数cnt,同时遍历typed字符串,看该字符是否在typed字符串里面,在则统计有多少连续的该字符,如果统计结果>=cnt,则true,否则为false。

Q1:如何遍历字符串,并找出每个字符连续出现的个数?

public void countNum(String name) {
    
    
		for (int i = 0; i < name.length(); i++) {
    
    
			int j = i + 1;// 从0开始,依次往后找
			int cnt = 1;
			// cnt设为1是因为,如果该字符是连续的,则cnt++,cnt就为2,表示2个相同字符
			// 如果不连续,那该字符出现1次
			while (j < name.length() && name.charAt(i) == name.charAt(j)) {
    
    
				j++;// 如果是连续的,继续往后,看有多少个连续的
				cnt++;
			}
			// while循环出来的j是下一个即将参与比较的字符,而循环体一次循环之后会i++
			// 所以i=j-1,让i回退一步,从而i++之后就是下一个即将参与比较的字符
			i = j - 1;
			System.out.println(name.charAt(i) +" "+ cnt);
		}
	}

结果:
在这里插入图片描述
Q2:对于typed字符串,也是采用上面的方法统计连续字符的个数吗?
可以,但是没有必要。
我们设置一个index,记录typed下标。index从0开始,通过while循环:typed.charAt(index)==name.charAt(i),判断typed的元素和name的元素是否匹配的,匹配则index++,在typed字符串中继续找是否存在相同的字符。此时也要设置cnt2=0,用于计算typed字符串有多少个连续的该字符,如果cnt2>=cnt,则说明是长按键入,否则返回false。

但是有很多细节没有考虑:
1.边界问题:如果name字符串都遍历完了,typed都还没有遍历完,则说明存在其他的字符,是name里面没有的。
2.如果name没有遍历完,而index已经越界了,则说明typed字符串不够拿来比较。
3.只有当typed.charAt(index)==name.charAt(i)才进行循环比较和计算,如果typed.charAt(index)!=name.charAt(i),说明字符不匹配,则不进入循环,直接返回false。

完整代码

public class LongPressedName {
    
    
	public static void main(String[] args) {
    
    
		LongPressedName test = new LongPressedName();
		boolean flag = test.isLongPressedName("alex", "alexxr");
		System.out.println(flag);
	}

	public boolean isLongPressedName(String name, String typed) {
    
    
		if (name.equals(typed))
			return true;
		int index = 0;
		for (int i = 0; i < name.length(); i++) {
    
    
			int j = i + 1;
			int cnt = 1;
			while (j < name.length() && name.charAt(i) == name.charAt(j)) {
    
    
				j++;
				cnt++;
			}
			i = j - 1;
			if (index >= typed.length() || typed.charAt(index) != name.charAt(i)) {
    
    
				return false;
			}
			int cnt2 = 0;
			while (index < typed.length() && typed.charAt(index) == name.charAt(i)) {
    
    
				index++;
				cnt2++;
			}
			if (cnt2 < cnt) {
    
    
				return false;
			}
		}
		if (index < typed.length()) {
    
    
			return false;
		}
		return true;
	}
}

做题反思

学到了:
(1)如何计算一个字符串的连续字符个数。
(2)考虑边界情况
end.

猜你喜欢

转载自blog.csdn.net/weixin_44998686/article/details/109203761