Tuesday, September 8, 2020

LeetCode [722] Remove Comments

 722. Remove Comments

Medium

Given a C++ program, remove comments from it. The program source is an array where source[i] is the i-th line of the source code. This represents the result of splitting the original source code string by the newline character \n.

In C++, there are two types of comments, line comments, and block comments.

The string // denotes a line comment, which represents that it and rest of the characters to the right of it in the same line should be ignored.

The string /* denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of */ should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string /*/ does not yet end the block comment, as the ending would be overlapping the beginning.

The first effective comment takes precedence over others: if the string // occurs in a block comment, it is ignored. Similarly, if the string /* occurs in a line or block comment, it is also ignored.

If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty.

There will be no control characters, single quote, or double quote characters. For example, source = "string s = "/* Not a comment. */";" will not be a test case. (Also, nothing else such as defines or macros will interfere with the comments.)

It is guaranteed that every open block comment will eventually be closed, so /* outside of a line or block comment always starts a new comment.

Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details.

After removing the comments from the source code, return the source code in the same format.

Example 1:

Input: 
source = ["/*Test program */", "int main()", "{ ", "  // variable declaration ", "int a, b, c;", "/* This is a test", "   multiline  ", "   comment for ", "   testing */", "a = b + c;", "}"]

The line by line code is visualized as below:
/*Test program */
int main()
{ 
  // variable declaration 
int a, b, c;
/* This is a test
   multiline  
   comment for 
   testing */
a = b + c;
}

Output: ["int main()","{ ","  ","int a, b, c;","a = b + c;","}"]

The line by line code is visualized as below:
int main()
{ 
  
int a, b, c;
a = b + c;
}

Explanation: 
The string /* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.

Example 2:

Input: 
source = ["a/*comment", "line", "more_comment*/b"]
Output: ["ab"]
Explanation: The original source string is "a/*comment\nline\nmore_comment*/b", where we have bolded the newline characters.  After deletion, the implicit newline characters are deleted, leaving the string "ab", which when delimited by newline characters becomes ["ab"].

Note:

  • The length of source is in the range [1, 100].
  • The length of source[i] is in the range [0, 80].
  • Every open block comment is eventually closed.
  • There are no single-quote, double-quote, or control characters in the source code.
  •  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 {
        public List<String> removeComments(String[] source) {
            List<String> code = new ArrayList<>();
            boolean isComments = false;
            StringBuilder newLine = new StringBuilder();
            for(String line : source){
                int i = 0;
                int n = line.length();
                while(i<n){  
                    if(isComments){//in between /* */
                        if(i<n && line.charAt(i)=='*' && i+1<n && line.charAt(i+1)=='/'){
                            isComments = false;
                            i += 2;
                        }else{
                            i++;
                        }
                    }else{
                        if(i<n && line.charAt(i)=='/' && i+1<n && line.charAt(i+1)=='*'){
                            i += 2;
                            isComments = true;
                        }else if(i<n && line.charAt(i)=='/' && i+1<n && line.charAt(i+1)=='/'){
                            break;
                        }else{
                            newLine.append(line.charAt(i++));
                        }
                    }
                }
                if(!isComments && newLine.length()>0){
                    code.add(newLine.toString());
                    newLine = new StringBuilder();
                }
            }
            return code;
        }
    }
    

    LeetCode [732] My Calendar III

     732. My Calendar III

    Hard

    Implement a MyCalendarThree class to store your events. A new event can always be added.

    Your class will have one method, book(int start, int end). Formally, this represents a booking on the half open interval [start, end), the range of real numbers x such that start <= x < end.

    A K-booking happens when K events have some non-empty intersection (ie., there is some time that is common to all K events.)

    For each call to the method MyCalendar.book, return an integer K representing the largest integer such that there exists a K-booking in the calendar.

    Your class will be called like this: MyCalendarThree cal = new MyCalendarThree(); MyCalendarThree.book(start, end)

    Example 1:

    MyCalendarThree();
    MyCalendarThree.book(10, 20); // returns 1
    MyCalendarThree.book(50, 60); // returns 1
    MyCalendarThree.book(10, 40); // returns 2
    MyCalendarThree.book(5, 15); // returns 3
    MyCalendarThree.book(5, 10); // returns 3
    MyCalendarThree.book(25, 55); // returns 3
    Explanation: 
    The first two events can be booked and are disjoint, so the maximum K-booking is a 1-booking.
    The third event [10, 40) intersects the first event, and the maximum K-booking is a 2-booking.
    The remaining events cause the maximum K-booking to be only a 3-booking.
    Note that the last event locally causes a 2-booking, but the answer is still 3 because
    eg. [10, 20), [10, 40), and [5, 15) are still triple booked.
    

     

    Note:

    • The number of calls to MyCalendarThree.book per test case will be at most 400.
    • In calls to MyCalendarThree.book(start, end), start and end are integers in the range [0, 10^9].
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    class MyCalendarThree {
        TreeMap<Integer, Integer> timeLine;
        public MyCalendarThree() {
            timeLine = new TreeMap<>();
        }
        
        public int book(int start, int end) {
            timeLine.put(start, timeLine.getOrDefault(start, 0)+1);
            timeLine.put(end, timeLine.getOrDefault(end, 0)-1);
            int ongoing = 0, ret = 0;
            for(int v : timeLine.values()){
                ongoing += v;
                ret = Math.max(ret, ongoing);
            }
            return ret;
        }
    }
    
    /**
     * Your MyCalendarThree object will be instantiated and called as such:
     * MyCalendarThree obj = new MyCalendarThree();
     * int param_1 = obj.book(start,end);
     */
    

    LeetCode [752] Open the Lock

     752. Open the Lock

    Medium

    You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.

    The lock initially starts at '0000', a string representing the state of the 4 wheels.

    You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.

    Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.

     

    Example 1:

    Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202"
    Output: 6
    Explanation:
    A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202".
    Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid,
    because the wheels of the lock become stuck after the display becomes the dead end "0102".
    

    Example 2:

    Input: deadends = ["8888"], target = "0009"
    Output: 1
    Explanation:
    We can turn the last wheel in reverse to move from "0000" -> "0009".
    

    Example 3:

    Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888"
    Output: -1
    Explanation:
    We can't reach the target without getting stuck.
    

    Example 4:

    Input: deadends = ["0000"], target = "8888"
    Output: -1
    

     

    Constraints:

    • 1 <= deadends.length <= 500
    • deadends[i].length == 4
    • target.length == 4
    • target will not be in the list deadends.
    • target and deadends[i] consist of digits only.
     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
    class Solution {
        public int openLock(String[] deadends, String target) {
            Set<String> deads = new HashSet<>();
            for(String d : deadends) deads.add(d);
            String start = "0000";
            if(deads.contains(start)) return -1;
            if(target.equals(start)) return 0;
            Queue<String> q = new LinkedList<>();
            Set<String> visited = new HashSet<>();
            q.add(start);
            visited.add(start);
    
            for(int turns = 1; !q.isEmpty(); turns++){
                for(int i=q.size(); i>0; --i){
                    String state = q.poll();
                    for(int j=0; j<4; ++j){
                        for(int d = 1; d<=9; d+=8){
                            StringBuilder state1 = new StringBuilder(state);
                            state1.setCharAt(j, (char)((state1.charAt(j)-'0'+d)%10+'0'));
                            String newState = state1.toString();   
                            if(newState.equals(target)) return turns;
                            if(!deads.contains(newState) && !visited.contains(newState)){
                                q.add(newState);
                            }
                            visited.add(newState);
                        }
                    }
                }
            }
            return -1;
        }
    }
    

    LeetCode [753] Cracking the Safe

     753. Cracking the Safe

    Hard

    There is a box protected by a password. The password is a sequence of n digits where each digit can be one of the first k digits 0, 1, ..., k-1.

    While entering a password, the last n digits entered will automatically be matched against the correct password.

    For example, assuming the correct password is "345", if you type "012345", the box will open because the correct password matches the suffix of the entered password.

    Return any password of minimum length that is guaranteed to open the box at some point of entering it.

     

    Example 1:

    Input: n = 1, k = 2
    Output: "01"
    Note: "10" will be accepted too.
    

    Example 2:

    Input: n = 2, k = 2
    Output: "00110"
    Note: "01100", "10011", "11001" will be accepted too.
    

     

    Note:

    1. n will be in the range [1, 4].
    2. k will be in the range [1, 10].
    3. k^n will be at most 4096.
     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
    class Solution {
        public String crackSafe(int n, int k) {
            StringBuilder pwd = new StringBuilder(new String(new char[n]).replace('\0', '0'));
            int total = (int)Math.pow(k, n);
            Set<String> visited = new HashSet<>();
            visited.add(pwd.toString());
            helper(pwd, total, visited, n, k);
            return pwd.toString();
        }
    
        boolean helper(StringBuilder pwd, int total, Set<String> visited, int n, int k){
            if(visited.size() == total) return true;
            String surfix = pwd.substring(pwd.length()-n+1);
            for(char c = '0'; c<'0'+k; c++){
                String surfix1 = surfix + c;
                if(!visited.contains(surfix1)){
                    pwd.append(c);
                    visited.add(surfix1);
                    if(helper(pwd, total, visited, n, k)) return true;
                    visited.remove(surfix1);
                    pwd.deleteCharAt(pwd.length()-1);
                }
            }
            return false;
        }
    }
    

    LeetCode [769] Max Chunks To Make Sorted

     769. Max Chunks To Make Sorted

    Medium

    Given an array arr that is a permutation of [0, 1, ..., arr.length - 1], we split the array into some number of "chunks" (partitions), and individually sort each chunk.  After concatenating them, the result equals the sorted array.

    What is the most number of chunks we could have made?

    Example 1:

    Input: arr = [4,3,2,1,0]
    Output: 1
    Explanation:
    Splitting into two or more chunks will not return the required result.
    For example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted.
    

    Example 2:

    Input: arr = [1,0,2,3,4]
    Output: 4
    Explanation:
    We can split into two chunks, such as [1, 0], [2, 3, 4].
    However, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible.
    

    Note:

    • arr will have length in range [1, 10].
    • arr[i] will be a permutation of [0, 1, ..., arr.length - 1].
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    class Solution {
        public int maxChunksToSorted(int[] arr) {
            int count = 0, max = 0;
            for(int i=0; i<arr.length; ++i){
                max = Math.max(max, arr[i]);
                if(max == i) count++;
            }
            return count;
        }
    }
    

    LeetCode [772] Basic Calculator III

     772. Basic Calculator III

    Hard

    Implement a basic calculator to evaluate a simple expression string.

    The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .

    The expression string contains only non-negative integers, +, -, *, / operators , open ( and closing parentheses ) and empty spaces . The integer division should truncate toward zero.

    You may assume that the given expression is always valid. All intermediate results will be in the range of [-2147483648, 2147483647].

    Some examples:

    "1 + 1" = 2
    " 6-4 / 2 " = 4
    "2*(5+5*2)/3+(6/2+8)" = 21
    "(2+6* 3+5- (3*14/7+2)*5)+3"=-12
     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
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    class Solution {
        public int calculate(String s) {
            Stack<Integer> nums = new Stack<>();
            Stack<Character> ops = new Stack<>();
            int v = 0;
            boolean hasV = false;
            s += '+';
    
            for(char c:s.toCharArray()){
                if(c==' ') continue;
                else if(Character.isDigit(c)){
                    v = v*10 + c - '0';
                    hasV = true;
                }else if(c=='('){
                    ops.push(c);
                }else if(c==')'){
                    if(hasV)
                        nums.push(v); v = 0; hasV = false;
                    while(!ops.empty() && ops.peek()!='(')
                        evaluate(nums, ops);   
                    ops.pop();             
                }else{//'+', '-'
                    if(hasV)
                        nums.push(v); v = 0; hasV = false;
                    while(!ops.empty() && precedence(ops.peek())>=precedence(c))
                        evaluate(nums, ops);
                    ops.push(c);
                }
            }
    
            return nums.pop();
        }
    
        int precedence(char op){
            switch(op){
                case '+' : return 0;
                case '-' : return 0;
                case '*' : return 1;
                case '/' : return 1;
                default: return -2;
            }
        }
    
        void evaluate(Stack<Integer> nums, Stack<Character> ops){
            int r = nums.pop();
            int l = nums.pop();
            char op = ops.pop();
            int result = 0;
            switch (op)
            {
                case '+' : result = l+r; break;
                case '-' : result = l-r; break;
                case '*' : result = l*r; break;
                case '/' : result = l/r; break;
                default: break;
            }
            nums.push(result);
        }
    }