文章最前: 我是Octopus,这个名字来源于我的中文名--章鱼;我热爱编程、热爱算法、热爱开源。所有源码在我的个人github ;这博客是记录我学习的点点滴滴,如果您对 Python、Java、AI、算法有兴趣,可以关注我的动态,一起学习,共同进步。
相关文章:
- LeetCode:55. Jump Game(跳远比赛)
- Leetcode:300. Longest Increasing Subsequence(最大增长序列)
- LeetCode:560. Subarray Sum Equals K(找出数组中连续子串和等于k)
文章目录:
题目描述:
你检查键盘的键入字符。 如果可能是你的朋友姓名,则返回True
,其中一些字符(可能没有)被长按。
例如1:
输入:name =“alex”,typed =“aaleex”
输出:true
说明:'alex'中的'a'和'e'被长按。
例如2:
输入:name =“laiden”,typed =“laiden”
输出:true
说明:没有必要长按任何字符。
java实现方式1:
/**
* 是不是长类型名字
*
* @param name 名字
* @param typed 类型
* @return 布尔值
*/
public boolean isLongPressedName(String name, String typed) {
if (name == null || name.length() < 1) {
return false;
}
if (name.charAt(name.length() - 1) != typed.charAt(typed.length() - 1)) {
return false;
}
if (name.charAt(0) != typed.charAt(0)) {
return false;
}
int i = 0;
int j = 0;
while (i < name.length()) {
if (name.charAt(i) == typed.charAt(j)) {
i++;
if (j < typed.length()) {
j++;
}
} else {
while (typed.charAt(j) == typed.charAt(j - 1)) {
j++;
}
if (name.charAt(i) != typed.charAt(j)) {
return false;
}
}
}
while (j < typed.length()) {
if (typed.charAt(j) != name.charAt(i - 1)) {
return false;
}
j++;
}
return j == typed.length();
}
时间复杂度:O(n)
空间复杂度:O(n)
python实现方式1:
# -*- coding:utf-8 -*-
'''
长压字符串
author:zhangyu
date:2020/2/10
'''
def is_long_pressed_name(name: str, typed: str) -> bool:
'''
判断是不是长安字符串
Args:
name: 名字
typed: 长按类型
Returns:
布尔值
'''
if name == None or len(name) < 1:
return False
if name[-1] != typed[-1]:
return False
if name[0] != typed[0]:
return False
i = 0
j = 0
while i < len(name):
if name[i] == typed[j]:
i += 1
if j < len(typed):
j += 1
else:
while typed[j] == typed[j - 1]:
j += 1
if name[i] != typed[j]:
return False
while j < len(typed):
if typed[j] != name[i - 1]:
return False
j += 1
return j == len(typed)
if __name__ == '__main__':
name = "dfuyalc"
typed = "dfuuyallc"
b = is_long_pressed_name(name, typed)
print(b)
时间复杂度:O(n)
空间复杂度:O(n)