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.
 

Constraints:

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

这题主要是要检测某个输入是否是原始输入多按了几个相同字母造成的。这里直接暴力去解了,肯定有更加高效的算法。

class Solution {
public:
    void getPattern(std::string &str,
                  std::vector<std::tuple<char, int>> &pattern) {
      char last_char = str[0];
      int count = 1;
      for (int i = 1; i < str.size(); i++) {
          if (str[i] == last_char) {
              ++count;
          } else {
              pattern.push_back(std::make_tuple(last_char, count));
              count = 1;
              last_char = str[i];
          }
      }
      if (count != 0) {
          pattern.push_back(std::make_tuple(last_char, count));
      }
  }
    
    bool isLongPressedName(string name, string typed) {
        int ni = 0, ti = 0;
        std::vector<std::tuple<char, int>> np;
        std::vector<std::tuple<char, int>> tp;

        getPattern(name, np);
        getPattern(typed, tp);

        if (np.size() != tp.size()) {
            return false;
        }
        for (int i = 0; i < tp.size(); i++) {
            if (std::get<0>(tp[i]) != std::get<0>(np[i])) {
                return false;
            }
            if (std::get<1>(tp[i]) < std::get<1>(np[i])) {
                return false;
            }
        }
        return true;
    }
};
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day