Tuesday, September 8, 2020

LeetCode [774] Minimize Max Distance to Gas Station

 774. Minimize Max Distance to Gas Station

Hard

On a horizontal number line, we have gas stations at positions stations[0], stations[1], ..., stations[N-1], where N = stations.length.

Now, we add K more gas stations so that D, the maximum distance between adjacent gas stations, is minimized.

Return the smallest possible value of D.

Example:

Input: stations = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], K = 9
Output: 0.500000

Note:

  1. stations.length will be an integer in range [10, 2000].
  2. stations[i] will be an integer in range [0, 10^8].
  3. K will be an integer in range [1, 10^6].
  4. Answers within 10^-6 of the true value will be accepted as correct.
 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
class Solution {
    double E = 1e-6;
    int compare(double a, double b)
    {
        if(Math.abs(a-b)<=E) return 0;
        else if(a>b) return 1;
        else return -1;
    }
    
    public double minmaxGasDist(int[] stations, int K) {
        double l = E, r = 2000;
        while(compare(l, r)<=0)
        {
            double mid = l + (r-l)/2.0;
     //       System.out.println(l + " " + r + " " + mid);
            if(valid(stations, K, mid))
            {
                if(compare(mid, 0)==0 || !valid(stations, K, mid-E)) return mid;
                r = mid-E;
            }else{
                l = mid+E;
            }
        }
        return l;
    }
    
    boolean valid (int[] stations, int K, double target)
    {  
        int n = stations.length;
        int added = 0;
        for(int i=1; i<n; ++i){
            double distance = (double)stations[i]-(double)stations[i-1];
            if(distance > target){
                added += (int)Math.floor(distance/target);
            }
            if(added>K) return false;
        }
        return true;
    }
}

LeetCode [792] Number of Matching Subsequences

 792. Number of Matching Subsequences

Medium

Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S.

Example :
Input: 
S = "abcde"
words = ["a", "bb", "acd", "ace"]
Output: 3
Explanation: There are three words in words that are a subsequence of S: "a", "acd", "ace".

Note:

  • All words in words and S will only consists of lowercase letters.
  • The length of S will be in the range of [1, 50000].
  • The length of words will be in the range of [1, 5000].
  • The length of words[i] will be in the range of [1, 50].
 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
class Solution {
    public int numMatchingSubseq(String S, String[] words) {
        List<StringBuilder>[] list = new List[128];
        for(char c = 'a'; c<='z'; c++) list[c] = new ArrayList<>();
        for(String w : words){
            list[w.charAt(0)].add(new StringBuilder(w));
        }
        int ret = 0;

        for(char c : S.toCharArray()){
            List<StringBuilder> temp = list[c];
            list[c] = new ArrayList<>();

            for(StringBuilder it : temp) {
                it.deleteCharAt(0);
                if(it.length()!=0){
                    list[it.charAt(0)].add(it);
                }else
                    ret++;
            }
        }

        return ret;
    }
}

LeetCode [802] Find Eventual Safe States

 802. Find Eventual Safe States

Medium

In a directed graph, we start at some node and every turn, walk along a directed edge of the graph.  If we reach a node that is terminal (that is, it has no outgoing directed edges), we stop.

Now, say our starting node is eventually safe if and only if we must eventually walk to a terminal node.  More specifically, there exists a natural number K so that for any choice of where to walk, we must have stopped at a terminal node in less than K steps.

Which nodes are eventually safe?  Return them as an array in sorted order.

The directed graph has N nodes with labels 0, 1, ..., N-1, where N is the length of graph.  The graph is given in the following form: graph[i] is a list of labels j such that (i, j) is a directed edge of the graph.

Example:
Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]]
Output: [2,4,5,6]
Here is a diagram of the above graph.

Illustration of graph

Note:

  • graph will have length at most 10000.
  • The number of edges in the graph will not exceed 32000.
  • Each graph[i] will be a sorted list of different integers, chosen within the range [0, graph.length - 1].
 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
class Solution {
    int n;
    boolean[] visited = new boolean[10000];
    boolean[] path = new boolean[10000];
    List<Integer> ret = new ArrayList<>();
    public List<Integer> eventualSafeNodes(int[][] graph) {
        n = graph.length;
        for(int node = 0; node<n; ++node){
            visited = new boolean[10000];
            path[node] = true;
            if(!hasCycle(node, graph)){
                ret.add(node);
            }
            path[node] = false;
        }
        return ret;
    }

    boolean hasCycle(int node, int[][] graph){
        visited[node] = true;
        for(int next:graph[node]){
                if(path[next]) return true;
                path[next] = true;
                if(!visited[next] && hasCycle(next, graph)) return true;
                path[next] = false;
        }
        return false;
    }
}

 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 {
    Set<Integer> unsafe = new HashSet<>();
    public List<Integer> eventualSafeNodes(int[][] graph) {
        int n = graph.length;
        Set<Integer> visited = new HashSet<>();
        
        for(int node = 0; node<n; ++node){
            visited.clear();
            Set<Integer> path = new HashSet<>();
            path.add(node);
            hasCycle(graph, node, path, visited);
        }
        
        List<Integer> list = new ArrayList<>();
        for(int i=0; i<n; ++i){
            if(!unsafe.contains(i)) list.add(i);
        }
        return list;
    }
    
    boolean hasCycle(int[][] graph, int node, Set<Integer> path, Set<Integer> visited){
        visited.add(node);
        for(int next : graph[node]){
            if(path.contains(next)){
                unsafe.addAll(path);
                return true;
            }
            if(visited.contains(next)) continue;
            path.add(next);
            if(hasCycle(graph, next, path, visited)) return true;
            path.remove(next);
        }
        return false;
    }
}

LeetCode [809] Expressive Words

 809. Expressive Words

Medium

Sometimes people repeat letters to represent extra feeling, such as "hello" -> "heeellooo", "hi" -> "hiiii".  In these strings like "heeellooo", we have groups of adjacent letters that are all the same:  "h", "eee", "ll", "ooo".

For some given string S, a query word is stretchy if it can be made to be equal to S by any number of applications of the following extension operation: choose a group consisting of characters c, and add some number of characters c to the group so that the size of the group is 3 or more.

For example, starting with "hello", we could do an extension on the group "o" to get "hellooo", but we cannot get "helloo" since the group "oo" has size less than 3.  Also, we could do another extension like "ll" -> "lllll" to get "helllllooo".  If S = "helllllooo", then the query word "hello" would be stretchy because of these two extension operations: query = "hello" -> "hellooo" -> "helllllooo" = S.

Given a list of query words, return the number of words that are stretchy. 

 

Example:
Input: 
S = "heeellooo"
words = ["hello", "hi", "helo"]
Output: 1
Explanation: 
We can extend "e" and "o" in the word "hello" to get "heeellooo".
We can't extend "helo" to get "heeellooo" because the group "ll" is not size 3 or more.

 

Constraints:

  • 0 <= len(S) <= 100.
  • 0 <= len(words) <= 100.
  • 0 <= len(words[i]) <= 100.
  • S and all words in words consist only of lowercase letters
 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
class Solution {
    public int expressiveWords(String S, String[] words) {
        int ret = 0;
        for(String w:words){
            if(valid(S,w)) ret++;
        }
        return ret;
    }

    boolean valid(String S, String w){
        int i = 0, j = 0, ns = S.length(), nw = w.length();
        while(i<ns && j<nw){
            if(S.charAt(i)!=w.charAt(j)) return false;
            int i1 = i, j1 = j;
            while(i1<ns && S.charAt(i1)==S.charAt(i)) i1++;
            while(j1<nw && w.charAt(j1)==w.charAt(j)) j1++;
            int cntS = i1-i, cntW = j1-j;
            if(cntS<cntW) return false;
            if(cntS>cntW && cntS<3) return false;
            i = i1;
            j = j1;
        }
        return i==ns && j==nw;
    }
}

LeetCode [821] Shortest Distance to a Character

 821. Shortest Distance to a Character

Easy

Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string.

Example 1:

Input: S = "loveleetcode", C = 'e'
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]

 

Note:

  1. S string length is in [1, 10000].
  2. C is a single character, and guaranteed to be in string S.
  3. All letters in S and C are lowercase.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
    public int[] shortestToChar(String S, char C) {
        int len = S.length();
        int[] ret = new int[len];

        int e = -1;
        for(int i=0; i<len; ++i)
        {
            if(S.charAt(i)==C) e = i;
            if(e==-1) ret[i] = len;
            else ret[i] = i-e;
        }

        e = len;
        for(int i=len-1; i>=0; --i)
        {
            if(S.charAt(i)==C) e = i;
            if(e<len) ret[i] = Math.min(ret[i], e-i);
        }

        return ret;
    }
}

Friday, September 4, 2020

LeetCode [833] Find And Replace in String

 833. Find And Replace in String

Medium

To some string S, we will perform some replacement operations that replace groups of letters with new ones (not necessarily the same size).

Each replacement operation has 3 parameters: a starting index i, a source word x and a target word y.  The rule is that if x starts at position i in the original string S, then we will replace that occurrence of x with y.  If not, we do nothing.

For example, if we have S = "abcd" and we have some replacement operation i = 2, x = "cd", y = "ffff", then because "cd" starts at position 2 in the original string S, we will replace it with "ffff".

Using another example on S = "abcd", if we have both the replacement operation i = 0, x = "ab", y = "eee", as well as another replacement operation i = 2, x = "ec", y = "ffff", this second operation does nothing because in the original string S[2] = 'c', which doesn't match x[0] = 'e'.

All these operations occur simultaneously.  It's guaranteed that there won't be any overlap in replacement: for example, S = "abc", indexes = [0, 1], sources = ["ab","bc"] is not a valid test case.

Example 1:

Input: S = "abcd", indexes = [0,2], sources = ["a","cd"], targets = ["eee","ffff"]
Output: "eeebffff"
Explanation: "a" starts at index 0 in S, so it's replaced by "eee".
"cd" starts at index 2 in S, so it's replaced by "ffff".

Example 2:

Input: S = "abcd", indexes = [0,2], sources = ["ab","ec"], targets = ["eee","ffff"]
Output: "eeecd"
Explanation: "ab" starts at index 0 in S, so it's replaced by "eee". 
"ec" doesn't starts at index 2 in the original S, so we do nothing.

Notes:

  1. 0 <= indexes.length = sources.length = targets.length <= 100
  2. 0 < indexes[i] < S.length <= 1000
  3. All characters in given inputs are lowercase letters.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
    public String findReplaceString(String S, int[] indexes, String[] sources, String[] targets) {
        List<int[]> sortedIndexesPairs = new ArrayList<>();//indexes[i], i
        for(int i=0; i<indexes.length; ++i){
            sortedIndexesPairs.add(new int[]{indexes[i], i});
        }
        Collections.sort(sortedIndexesPairs, Comparator.comparing(p -> -p[0]));
        for(int[] p : sortedIndexesPairs){
            int i = p[0];//index of S
            int j = p[1];//index of indexes;
            String s = sources[j], t = targets[j];
            if(S.substring(i, i+s.length()).equals(s)){
                S = S.substring(0, i) + t + S.substring(i+s.length());
            }
        }
        return S;
    }
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
    public String findReplaceString(String S, int[] indexes, String[] sources, String[] targets) {
        Map<Integer, Integer> map = new HashMap<>();
        int n = indexes.length;
        for(int i=0; i<n; ++i) map.put(indexes[i], i);
        Arrays.sort(indexes);
        String tmp = S;
        for(int i = n-1; i>=0; --i){
            int l = indexes[i];
            int index = map.get(l);
            int len = sources[index].length();
            String str = S.substring(l, l+len);
            if(!str.equals(sources[index])) continue;
            tmp = S.substring(0, l)+targets[index]+tmp.substring(l+sources[index].length());
        }
        return tmp;
    }
}