LeetCode 925 - Long Pressed Name


https://leetcode.com/problems/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.

Approach 1: Group into Blocks
For a string like S = 'aabbbbccc', we can group it into blocks groupify(S) = [('a', 2), ('b', 4), ('c', 3)], that consist of a key 'abc' and a count [2, 4, 3].
Then, the necessary and sufficient condition for typed to be a long-pressed version of name is that the keys are the same, and each entry of the count of typed is at least the entry for the count of name.
For example, 'aaleex' is a long-pressed version of 'alex': because when considering the groups [('a', 2), ('l', 1), ('e', 2), ('x', 1)] and [('a', 1), ('l', 1), ('e', 1), ('x', 1)], they both have the key 'alex', and the count [2,1,2,1] is at least [1,1,1,1] when making an element-by-element comparison (2 >= 1, 1 >= 1, 2 >= 1, 1 >= 1).

  public boolean isLongPressedName(String name, String typed) {
    Group g1 = groupify(name);
    Group g2 = groupify(typed);
    if (!g1.key.equals(g2.key))
      return false;

    for (int i = 0; i < g1.count.size(); ++i)
      if (g1.count.get(i) > g2.count.get(i))
        return false;
    return true;
  }

  public Group groupify(String S) {
    StringBuilder key = new StringBuilder();
    List<Integer> count = new ArrayList();
    int anchor = 0;
    int N = S.length();
    for (int i = 0; i < N; ++i) {
      if (i == N - 1 || S.charAt(i) != S.charAt(i + 1)) { // end of group
        key.append(S.charAt(i));
        count.add(i - anchor + 1);
        anchor = i + 1;
      }
    }

    return new Group(key.toString(), count);
  }

class Group {
  String key;
  List<Integer> count;

  Group(String k, List<Integer> c) {
    key = k;
    count = c;
  }
}


Approach 2: Two Pointer
As in Approach 1, we want to check the key and the count. We can do this on the fly.
Suppose we read through the characters name, and eventually it doesn't match typed.
There are some cases for when we are allowed to skip characters of typed. Let's use a tuple to denote the case (nametyped):
  • In a case like ('aab', 'aaaaab'), we can skip the 3rd, 4th, and 5th 'a' in typed because we have already processed an 'a' in this block.
  • In a case like ('a', 'b'), we can't skip the 1st 'b' in typed because we haven't processed anything in the current block yet.
Algorithm
This leads to the following algorithm:
  • For each character in name, if there's a mismatch with the next character in typed:
    • If it's the first character of the block in typed, the answer is False.
    • Else, discard all similar characers of typed coming up. The next (different) character coming must match.
Also, we'll keep track on the side of whether we are at the first character of the block.

  public boolean isLongPressedName(String name, String typed) {
    int j = 0;
    for (char c : name.toCharArray()) {
      if (j == typed.length())
        return false;

      // If mismatch...
      if (typed.charAt(j) != c) {
        // If it's the first char of the block, ans is false.
        if (j == 0 || typed.charAt(j - 1) != typed.charAt(j))
          return false;

        // Discard all similar chars
        char cur = typed.charAt(j);
        while (j < typed.length() && typed.charAt(j) == cur)
          j++;

        // If next isn't a match, ans is false.
        if (j == typed.length() || typed.charAt(j) != c)
          return false;
      }

      j++;
    }

    return true;

  }

X. https://zhanghuimeng.github.io/post/leetcode-925-long-pressed-name-and-weekly-contest-107/
https://www.acwing.com/solution/leetcode/content/584/
同时从前往后遍历两个字符串,每次分别找出两个字符串中相同字母的一段,如果:

字母相同;
name中该段的长度小于等于typed中该段的长度;
则说明该段字母合法,否则说明该段字母不合法。

如果所有相同字母段都合法,则返回true,否则返回false。

https://leetcode.com/problems/long-pressed-name/discuss/183929/C++-2-lines-accepted-and-5-lines-accurate
    bool isLongPressedName(string name, string typed) {
        int n = name.size(), m = typed.size();
        if (n > m) return false;
        int i = 0, j = 0;
        while (i < n || j < m) {
            if (i < n && typed[j] == name[i]) i++, j++;
            else if (i > 0 && typed[j] == name[i - 1]) j++;
            else break;
        }
        if (i == n && j == m) return true;
        return false;
    }
https://leetcode.com/problems/long-pressed-name/discuss/183994/C%2B%2BJavaPython-Two-Pointers


    public boolean isLongPressedName(String name, String typed) {
        int i = 0, m = name.length(), n = typed.length();
        for (int j = 0; j < n; ++j)
            if (i < m && name.charAt(i) == typed.charAt(j))
                ++i;
            else if (j == 0 || typed.charAt(j) != typed.charAt(j - 1))
                return false;
        return i == m;
    }

http://www.noteanddata.com/leetcode-925-Long-Pressed-Name-solution-note.html
public boolean isLongPressedName(String name, String typed) {
    int i = 0, j = 0;
    while(i < name.length() && j < typed.length()) {
        if(name.charAt(i) == typed.charAt(j)) {
            i++;
            j++;
        }
        else {
            if(j == 0 || typed.charAt(j) != typed.charAt(j-1)) return false;
            j++;                                
        }
    }
    if(i != name.length()) return false;
    while(j < typed.length()) {
        if(typed.charAt(j) != typed.charAt(j-1)) return false;
        j++;
    }
    return true;
}

X. https://zhuanlan.zhihu.com/p/50564246
这个题目是对两个字符串进行操作,很容易想到双指针,如果name[i]和typed[j]相等,那么就都往下走一步,当不相等时,由于长按,如果typed[j] == typed[j-1],可以让j++。 最后i要等于name.length。
    def isLongPressedName(self, name, typed):
        """
        :type name: str
        :type typed: str
        :rtype: bool
        """
        idx = 0
        for i in range(len(typed)):
            if idx < len(name) and name[idx] == typed[i]:
                idx += 1
            elif i == 0 or typed[i] != typed[i-1]:
                return False
        return idx == len(name)

X.
https://blog.csdn.net/fuxuemingzhu/article/details/83245395
思想是,使用两个指针,分别指向名字和输入字符串,然后判断对应位置是否能够对应的上。具体做法是统计两个字符串中相同的字符串重复出现了多少次。我用一个变量指向name,每次向后移动,在每次开始的时候需要保存这个字符,然后我们需要找一下每个字符串后面有多少个相同的字符。最后需要判断,如果输入的这个字符的个数小于名字里面有的,那么就是输入错误了。当所有的判断都结束没有返回错误,那么就是成功了。
    def isLongPressedName(self, name, typed):
        """
        :type name: str
        :type typed: str
        :rtype: bool
        """
        M = len(name)
        N = len(typed)
        i, j = 0, 0
        while i < M:
            c_i = name[i]
            count_i = 0
            count_j = 0
            while i < M and name[i] == c_i:
                i += 1
                count_i += 1
            while j < N and typed[j] == c_i:
                j += 1
                count_j += 1
            if count_j < count_i:
                return False
        return True
https://leetcode.com/problems/long-pressed-name/discuss/183965/Short-Java-Solution
public boolean isLongPressedName(String nameStr, String typeStr) {
        char[] name = nameStr.toCharArray(), typed = typeStr.toCharArray();
        int n = 0, t = 0;
        while (n < name.length && t < typed.length) {
            int need = 1;
            char c = name[n++];
            while (n < name.length && c == name[n]) {
                n++;
                need++;
            }
            while (t < typed.length && typed[t] == c) {
                need--;
                t++;
            }
            if (need > 0)
                return false;
        }
        return n == name.length && t == typed.length;
    }
X.
TODO
https://leetcode.com/problems/long-pressed-name/discuss/184488/Java-one-pass-solution-4ms-with-O(1)-extra-space
 public boolean isLongPressedName(String name, String typed) {
  int difference = 0;
  for (int i = 0; i < typed.length();) {
 //letters are equal -> go next
   if (difference <= i && i - difference < name.length() && typed.charAt(i) == name.charAt(i - difference)) {
    i++;
   } 
  // letters are not equal,  but we can link typed letter to name letter from the previous iteration
  else if (difference < i && i - difference - 1 < name.length() && typed.charAt(i) == name.charAt(i - difference - 1)) {
    difference++;
   } else return false;
  }
 // check that at the end of name there's no odd symbols
    return typed.length() - difference == name.length();
 }
X. 暴力的做法


    bool isLongPressedName(string name, string typed) {
        vector<pair<char, int>> press1, press2;
        for (char ch: name) {
            if (press1.size() == 0 || press1.back().first != ch)
                press1.emplace_back(ch, 1);
            else
                press1.back().second++;
        }
        for (char ch: typed) {
            if (press2.size() == 0 || press2.back().first != ch)
                press2.emplace_back(ch, 1);
            else
                press2.back().second++;
        }
        if (press1.size() != press2.size()) return false;
        for (int i = 0; i < press1.size(); i++)
            if (press1[i] > press2[i])
                return false;
        return true;
    }


Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts