925. Long Pressed Name

题目链接:https://leetcode.com/problems/long-pressed-name/description/

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.

思路:

  • typed 符合要求,则typed 的 length(长度)满足条件:typed.length() >= name.length();
  • i, j分别是指向nametyped的下标,i, j下标初始值都为0;
  1. name[i] == typed[j] 时,i, j 向后移动一个单位;
  2. name[i] != typed[j] 时,判断 typed[j] 是否等于name[i-1] (name[i-1] == typed[j-1]);
  3. typed[j] != name[j-1] 则 typed 不满足,返回false。若 typed[j] == name[i-1], ++j,直至 typed[j] != name[i-1],执行步骤2。

 注意:根据上面的分析,需要用一个字符变量来存储name[i]的值,该字符变量初始化为空字符

编码如下

 1 class Solution {
 2 public:
 3     bool isLongPressedName(string name, string typed) {
 4         // name的长度 大于 typed的长度时不符合
 5         if (name.length() > typed.length()) return false;
 6         
 7         char pre = ' ';                  // 存储name[i]的值,初始化为空字符
 8         int indexOfName = 0;      // 指示name的下标   
 9         
10         for (int i = 0; i < typed.length(); ++i)
11         {
12             if (name[indexOfName] != typed[i] && pre == ' ')
13                 return false;
14             
15             if (name[indexOfName] == typed[i])
16             {
17                 pre = name[indexOfName];
18                 indexOfName++;
19             }
20             else
21             {
22                 if (pre == typed[i])
23                     continue;
24                 else
25                     return false;
26             }
27         }
28         
29         if (indexOfName != name.length()) return false;
30         
31         return true;
32         
33     }
34         
35 };        

猜你喜欢

转载自www.cnblogs.com/ming-1012/p/9899269.html