LeetCode周赛#107 Q1 Long Pressed Name

题目来源:https://leetcode.com/contest/weekly-contest-107/problems/long-pressed-name/

问题描述

925. Long Pressed Name

Your friend is typing his name into a keyboard.  Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times.

You examine the typed characters of the keyboard.  Return True if it is possible that it was your friends name, with some characters (possibly none) being long pressed.

 

Example 1:

Input: name = "alex", typed = "aaleex"
Output: true
Explanation: 'a' and 'e' in 'alex' were long pressed.

Example 2:

Input: name = "saeed", typed = "ssaaedd"
Output: false
Explanation: 'e' must have been pressed twice, but it wasn't in the typed output.

Example 3:

Input: name = "leelee", typed = "lleeelee"
Output: true

Example 4:

Input: name = "laiden", typed = "laiden"
Output: true
Explanation: It's not necessary to long press any character.

 

Note:

  1. name.length <= 1000
  2. typed.length <= 1000
  3. The characters of name and typed are lowercase letters.

------------------------------------------------------------

题意

给定两个字符串name和typed,规定typed是由name中的一些字符重复打印造成的,问给定的typed能否由给定的name生成。

------------------------------------------------------------

思路

设置两个指针i和j,分别指向name和typed中的字符,统计name和typed中字符连续出现次数进行比较,如果name中的某一字符连续出现次数多于typed中的字符,则不能匹配。注意name中最后一个字符不在typed中的判断。

------------------------------------------------------------

代码

class Solution {
public:
    bool isLongPressedName(string name, string typed) {
        int i = 0, j = 0, leni = name.size(), lenj = typed.size();
        char ch;
        int cnt = 0;
        while (i<leni && j <lenj)
        {
            ch = name[i++];
            cnt = 1;
            while (i<leni && name[i] == ch)
            {
                i++;
                cnt++;
            }
            while (j<lenj && typed[j] == ch)
            {
                j++;
                cnt--;
            }
            if (cnt > 0)
            {
                return false;
            }
        }
        if (i < leni)           //some characters in "name" was still numatched
        {
            return false;
        }
        else
        {
            return true;
        }
    }
};

猜你喜欢

转载自blog.csdn.net/da_kao_la/article/details/83268094