Friday, September 4, 2020

LeetCode [843] Guess the Word

843. Guess the Word
Hard

This problem is an interactive problem new to the LeetCode platform.

We are given a word list of unique words, each word is 6 letters long, and one word in this list is chosen as secret.

You may call master.guess(word) to guess a word.  The guessed word should have type string and must be from the original list with 6 lowercase letters.

This function returns an integer type, representing the number of exact matches (value and position) of your guess to the secret word.  Also, if your guess is not in the given wordlist, it will return -1 instead.

For each test case, you have 10 guesses to guess the word. At the end of any number of calls, if you have made 10 or less calls to master.guess and at least one of these guesses was the secret, you pass the testcase.

Besides the example test case below, there will be 5 additional test cases, each with 100 words in the word list.  The letters of each word in those testcases were chosen independently at random from 'a' to 'z', such that every word in the given word lists is unique.

Example 1:
Input: secret = "acckzz", wordlist = ["acckzz","ccbazz","eiowzz","abcczz"]

Explanation:

master.guess("aaaaaa") returns -1, because "aaaaaa" is not in wordlist.
master.guess("acckzz") returns 6, because "acckzz" is secret and has all 6 matches.
master.guess("ccbazz") returns 3, because "ccbazz" has 3 matches.
master.guess("eiowzz") returns 2, because "eiowzz" has 2 matches.
master.guess("abcczz") returns 4, because "abcczz" has 4 matches.

We made 5 calls to master.guess and one of them was the secret, so we pass the test case.

Note:  Any solutions that attempt to circumvent the judge will result in disqualification.

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
 * // This is the Master's API interface.
 * // You should not implement it, or speculate about its implementation
 * interface Master {
 *     public int guess(String word) {}
 * }
 */
class Solution {
        int match(String w1, String w2) {
            int cnt = 0;
            for (int i = 0; i < 6; ++i) {
                if (w1.charAt(i) == w2.charAt(i))
                    cnt++;
            }
            return cnt;
        }
        public void findSecretWord(String[] wordlist, Master master) {
            while (true) {
                Map<String, Integer> count = new HashMap<>();
                int min0 = Integer.MAX_VALUE;
                String guessWord = "";
                for (String w : wordlist) {
                    for (String w1 : wordlist) {
                        if (match(w, w1) == 0) {
                            count.put(w, count.getOrDefault(w, 0) + 1);
                        }
                    }
                }
                for (String w : wordlist) {
                    if (count.getOrDefault(w, 0) < min0) {
                        min0 = count.getOrDefault(w, 0);
                        guessWord = w;
                    }
                }
                int x = master.guess(guessWord);
                if (x == 6)
                    break;
                List<String> wordlist2 = new ArrayList<>();
                for (String w : wordlist) {
                    if (match(w, guessWord) == x)
                        wordlist2.add(w);
                }
                wordlist = wordlist2.toArray(new String[0]);
            }
        }
}

LeetCode [844] Backspace String Compare

 844. Backspace String Compare

Easy

Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.

Note that after backspacing an empty text, the text will continue empty.

Example 1:

Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S and T become "ac".

Example 2:

Input: S = "ab##", T = "c#d#"
Output: true
Explanation: Both S and T become "".

Example 3:

Input: S = "a##c", T = "#a#c"
Output: true
Explanation: Both S and T become "c".

Example 4:

Input: S = "a#c", T = "b"
Output: false
Explanation: S becomes "c" while T becomes "b".

Note:

  • 1 <= S.length <= 200
  • 1 <= T.length <= 200
  • S and T only contain lowercase letters and '#' characters.

Follow up:

  • Can you solve it in O(N) time and O(1) space?
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
    public boolean backspaceCompare(String S, String T) {
        return process(S).equals(process(T));
    }

    String process(String S){
        StringBuilder sb = new StringBuilder();
        for(char c : S.toCharArray()){
            if(c=='#'){
                if(sb.length()>0) sb.deleteCharAt(sb.length()-1);
            }else{
                sb.append(c);
            }
        }
        return sb.toString();
    }
}

LeetCode [846] Hand of Straights

 846. Hand of Straights

Medium

Alice has a hand of cards, given as an array of integers.

Now she wants to rearrange the cards into groups so that each group is size W, and consists of W consecutive cards.

Return true if and only if she can.

 

    Example 1:

    Input: hand = [1,2,3,6,2,3,4,7,8], W = 3
    Output: true
    Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8].

    Example 2:

    Input: hand = [1,2,3,4,5], W = 4
    Output: false
    Explanation: Alice's hand can't be rearranged into groups of 4.
    

     

    Constraints:

    • 1 <= hand.length <= 10000
    • 0 <= hand[i] <= 10^9
    • 1 <= W <= hand.length
    Note: This question is the same as 1296: https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    class Solution {
        public boolean isNStraightHand(int[] hand, int W) {
            Map<Integer, Integer> count = new TreeMap<>();
            for(int i : hand) count.put(i, count.getOrDefault(i, 0)+1);
            for(int k : count.keySet()){
                if(count.get(k)==0) continue;
                int last = k + W-1;
                for(int j=last; j>=k; --j){
                    if(count.getOrDefault(j, 0) < count.get(k)) return false;
                    count.put(j, count.get(j)-count.get(k));
                }
            }
            return true;
        }
    }
    

    LeetCode [914] X of a Kind in a Deck of Cards

     914. X of a Kind in a Deck of Cards

    Easy

    In a deck of cards, each card has an integer written on it.

    Return true if and only if you can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where:

    • Each group has exactly X cards.
    • All the cards in each group have the same integer.

     

    Example 1:

    Input: deck = [1,2,3,4,4,3,2,1]
    Output: true
    Explanation: Possible partition [1,1],[2,2],[3,3],[4,4].
    

    Example 2:

    Input: deck = [1,1,1,2,2,2,3,3]
    Output: false´
    Explanation: No possible partition.
    

    Example 3:

    Input: deck = [1]
    Output: false
    Explanation: No possible partition.
    

    Example 4:

    Input: deck = [1,1]
    Output: true
    Explanation: Possible partition [1,1].
    

    Example 5:

    Input: deck = [1,1,2,2,2,2]
    Output: true
    Explanation: Possible partition [1,1],[2,2],[2,2].
    

     

    Constraints:

    • 1 <= deck.length <= 10^4
    • 0 <= deck[i] < 10^4
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    class Solution {
        public boolean hasGroupsSizeX(int[] deck) {
            Map<Integer, Integer> count = new HashMap<>();
            for(int i : deck){
                count.put(i, count.getOrDefault(i, 0) + 1);
            }
    
            int ret = 0;
            for(int i : count.values()){
                ret = gcd(i, ret);
            }
            return ret>1;
        }
    
        int gcd(int a, int b){
            if(b==0) return a;
            else return gcd(b, a%b);
        }
    }
    

    LeetCode [925] Long Pressed Name

     925. Long Pressed Name

    Easy

    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.
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    class Solution {
        public boolean isLongPressedName(String name, String typed) {
            int p1 = 0, p2 = 0, n1 = name.length(), n2 = typed.length();
            while(p1<n1 && p2<n2){
                if(name.charAt(p1)!=typed.charAt(p2)) return false;
                int q1 = p1+1, q2 = p2+1;
                while(q1<n1 && name.charAt(q1)==name.charAt(p1)) q1++;
                while(q2<n2 && typed.charAt(q2)==typed.charAt(p2)) q2++;
                int c1 = q1-p1;
                int c2 = q2-p2;
                if(c2<c1) return false;
                p1 = q1;
                p2 = q2;
            }
            return p1==n1 && p2==n2;
        }
    }
    

    LeetCode [946] Validate Stack Sequences

     946. Validate Stack Sequences

    Medium

    Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.

     

    Example 1:

    Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
    Output: true
    Explanation: We might do the following sequence:
    push(1), push(2), push(3), push(4), pop() -> 4,
    push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
    

    Example 2:

    Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
    Output: false
    Explanation: 1 cannot be popped before 2.
    

     

    Constraints:

    • 0 <= pushed.length == popped.length <= 1000
    • 0 <= pushed[i], popped[i] < 1000
    • pushed is a permutation of popped.
    • pushed and popped have distinct values.
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    class Solution {
        public boolean validateStackSequences(int[] pushed, int[] popped) {
            Stack<Integer> stk = new Stack<>();
            int i = 0, j = 0, n = pushed.length;
            while(i<n || j<n){
                if(!stk.isEmpty() && popped[j]==stk.peek()){
                    stk.pop();
                    j++;
                }else if(i<n){
                    stk.push(pushed[i++]);
                }else{
                    return false;
                }
            }
            return true;
        }
    }
    


    YMSF

    4. 酒似遛的变体,stack的模拟操作,这个stack push的rule是必须先放k, 才能放k+1,输入是0到n的permutation,代表pop出stack的顺序,问你给定的输入是否能实现

    一个valid的输入例子是(4,3,5,2,1,0),从0一值push到4,然后pop 4,3,然后push 5,然后pop 5,继续pop 2,1,0

    第四题,提供一个思路,因为输入的array A代表pop的order,当traverse A的时候,想要A能pop,则比A小且>= 0的数字都必须在这之前都push到stack上,所以对于A的判断,是要么需要push,要么需要pop

    我觉得是这样:push的rule是必须先放k, 才能放k+1,意思就是push的顺序就是0,1 2 3.。。然后输入是0到n的permutation, 那自然就变成的楼主说的那道题

    请教LZ 第四题的思路。感觉跟利口那题还是不太一样。或者我确实没想明白,能否大概share 下思路,或者 判断 不合理 输入的pattern。

    我能想到一些不合理的,但是不太能 归纳起来成为 规律。


    YMSF

    第二轮,给一串input,一串output,判断output是否有可能是input用stack输出的结果。followup:只能使用O(1)space。

    楼主第二题,这个是distinct的value吗?还是可以有重复值?

    没有重复值


    FOLLOW UP,INPUT和OUTPUT都是存在一个类似ARRAY的结构里面吗?如果是这样的话,O(1)是不是只要拿存INPUT的ARRAY模拟STACK操作就好


    好像只用O1 space无法用array模拟stack吧…

    我最后做出来是n^2的time complexity,在output是input的index的情况下

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    //o(n) space
    class Solution {
        //pushed is working as a stack
        public boolean validateStackSequences(int[] pushed, int[] popped) {
            int n = pushed.length;
            int i = 0, j = 0;
            for(int x : pushed){
                pushed[i] = x;
                while(i>=0 && pushed[i]==popped[j]){
                    i--;
                    j++;
                }
                i++;
            }
            
            return i==0;
        }
    }
    

    LeetCode [947] Most Stones Removed with Same Row or Column

     947. Most Stones Removed with Same Row or Column

    Medium

    On a 2D plane, we place stones at some integer coordinate points.  Each coordinate point may have at most one stone.

    Now, a move consists of removing a stone that shares a column or row with another stone on the grid.

    What is the largest possible number of moves we can make?

     

    Example 1:

    Input: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
    Output: 5
    

    Example 2:

    Input: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]
    Output: 3
    

    Example 3:

    Input: stones = [[0,0]]
    Output: 0
    

     

    Note:

    1. 1 <= stones.length <= 1000
    2. 0 <= stones[i][j] < 10000
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    class Solution {
        int isLands = 0;
        Map<Integer, Integer> f = new HashMap<>();
        public int removeStones(int[][] stones) {
            for(int[] s : stones){
                if(!f.containsKey(s[0])){
                    f.put(s[0], s[0]);
                    isLands ++;
                }
                
                if(!f.containsKey(~s[1])){
                    f.put(~s[1], ~s[1]);
                    isLands ++;
                }
            }
            for(int[] s : stones){
                union(s[0], ~s[1]);
            }
            return stones.length - isLands;
        }
    
        int find(int x){
            if(x == f.get(x)) return x;
            else return find(f.get(x));
        }
    
        void union(int x, int y){
            x = find(x);
            y = find(y);
            if(x!=y){
                isLands--;
                f.put(x, y);
            }
        }
    }