美文网首页
# LeetCode 925. Long Pressed Nam

# LeetCode 925. Long Pressed Nam

作者: 微微笑的蜗牛 | 来源:发表于2019-10-24 12:17 被阅读0次

问题

问题描述:你朋友正在用键盘打印他的名字,有时打印一个字符,键可能会被长按,因此该字符会被打印多次。

检查键盘中打印的字符,如果它是你朋友的名字,则返回true

栗子1:

输入: name = "alex", typed = "aaleex"
输出: true
'a' 和 'e' 是长按的字符。

栗子2:

输入: name = "saeed", typed = "ssaaedd"
输出: false
'e'应该被打印 2 次。

栗子3:

输入: name = "leelee", typed = "lleeelee"
输出: true

'l' 和 'e' 是长按的字符。

栗子4:

输入:name = "laiden", typed = "laiden"
输出:true
和 name 相等,不需要长按。

注意:

1. name.length <= 1000
2. typed.length <= 1000
3. 名字和打印的字符都是小写字母。

想看英文的戳这里:原题地址

解题思路

主要思路:因为有可能出现某个字符会被长按,那么会出现 typed 中某个字符的个数会大于原来的数量,所以只需要对比 nametyped

当字符相等时,分别计算 nametyped 中该字符的个数,如果typed中字符的个数 >= name中的,则可判定为刚好键入该字符或者长按该字符,满足条件。

Swift 代码:

class Solution {
    func isLongPressedName(_ name: String, _ typed: String) -> Bool {
        var i = 0
        var j = 0
        
        let nameList = Array(name)
        let typedList = Array(typed)
        
        // 分别遍历计算出 name, typed 相同的字符,进行比较,如果相同且typed中的字符数>name的,则继续。
        // alex, aaleex
        while i < nameList.count {

            // 如果当前字符相等
            if j < typedList.count, nameList[i] == typedList[j] {
                // 计算 name 中相同字符的个数
                var c1 = 1                
                while i + 1 < nameList.count, nameList[i] == nameList[i+1] {
                    i += 1
                    c1 += 1
                }
                
                // 计算 type 中相同字符的个数
                var c2 = 1
                while j + 1 < typedList.count, typedList[j] == typedList[j+1] {
                    j += 1
                    c2 += 1
                }
                
                // 不满足
                if c2 < c1 {
                    return false
                } else {
                    i += 1
                    j += 1
                }
            } else {
                return false
            }
        }
        
        // typed 中还有其他字符,不满足
        if j < typedList.count {
            return false
        }
        
        return true
    }
}

相关文章

网友评论

      本文标题:# LeetCode 925. Long Pressed Nam

      本文链接:https://www.haomeiwen.com/subject/zmvzectx.html