Wednesday, August 28, 2019

Remove2ConsecutiveCharInString

给一个string s,如果s_i == s_i+1,移除这两个characters,得到一个新的string,重复这个过程,返回最终的string。比如,
"aabbccd" -> "d",‍‌‍‍‍‌‌‌‌‍‍‍‍‌‌‌‌‍ "aabbac" -> "aaac" -> "ac"

Given a string "s", remove all sub strings with two consecutive chars. 

 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
#include "misc.h"

class Solution
{
public:
    string Remove(string s)
    {
        bool cont = true;
        while (cont)
        {
            cont = false;
            int i = 1, sz = s.size();
            while(i<sz){
                if(s[i]!=s[i-1]){
                    i++;
                }else{
                    int start = i-1;
                    while(i<sz && s[i]==s[start]) i++;
                    int len = i-start;//substring with same char
                    cont = true;
                    if(len%2==0){
                        s.erase(start, len);
                        i -= len;
                    }else{
                        s.erase(start, len-1);
                        i -= (len-1);//i points to the first char after the removed string
                    }
                }
            }
        }
        return s;
    }
};

int main()
{
    Solution sol;
    cout<<sol.Remove("aabbccd")<<endl;
    cout<<sol.Remove("eddegfsaabbccd")<<endl;
    return 0;
}

Sunday, August 25, 2019

LeetCode [465] Optimal Account Balancing

465. Optimal Account Balancing
Hard
A group of friends went on holiday and sometimes lent each other money. For example, Alice paid for Bill's lunch for $10. Then later Chris gave Alice $5 for a taxi ride. We can model each transaction as a tuple (x, y, z) which means person x gave person y $z. Assuming Alice, Bill, and Chris are person 0, 1, and 2 respectively (0, 1, 2 are the person's ID), the transactions can be represented as [[0, 1, 10], [2, 0, 5]].
Given a list of transactions between a group of people, return the minimum number of transactions required to settle the debt.
Note:
  1. A transaction will be given as a tuple (x, y, z). Note that x ≠ y and z > 0.
  2. Person's IDs may not be linear, e.g. we could have the persons 0, 1, 2 or we could also have the persons 0, 2, 6.
Example 1:
Input:
[[0,1,10], [2,0,5]]

Output:
2

Explanation:
Person #0 gave person #1 $10.
Person #2 gave person #0 $5.

Two transactions are needed. One way to settle the debt is person #1 pays person #0 and #2 $5 each.
Example 2:
Input:
[[0,1,10], [1,0,1], [1,2,5], [2,0,5]]

Output:
1

Explanation:
Person #0 gave person #1 $10.
Person #1 gave person #0 $1.
Person #1 gave person #2 $5.
Person #2 gave person #0 $5.

Therefore, person #1 only need to give person #0 $4, and all debt is settled.
 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
class Solution {
public:
    int minTransfers(vector<vector<int>>& transactions) {
        map<int, int> mp;//id, debt
        for(auto& p:transactions){
            mp[p[0]] -= p[2];
            mp[p[1]] += p[2];
        }
        vector<int> debts;
        for(auto& p:mp){
             debts.push_back(p.second);
        }
 
        int ret = INT_MAX;//min # transactions
        dfs(debts, 0, debts.size(), ret, 0);
        return ret;
    }
    
    //clear up debts[pos]
    void dfs(vector<int>& debts, int pos, int sz, int& ret, int trans){
        if(debts[pos]==0){
            if(pos==sz-1) ret = min(ret, trans);
            else dfs(debts, pos+1, sz, ret, trans);//no transaction needed to clear up debts[pos]
        }
        
        int d = debts[pos];
        debts[pos] = 0;
        for(int i=pos+1; i<sz; ++i){
            if(debts[i]*d>=0) continue;
            if(i>pos+1 && debts[i]==debts[i-1]) continue;
            debts[i] += d;
            dfs(debts, pos+1, sz, ret, trans+1);
            debts[i] -= d;
        }
        debts[pos] = d;
    }
};

 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
class Solution {
    public int minTransfers(int[][] transactions) {
        Map<Integer, Integer> bal = new HashMap<>();
        for(int[] t : transactions){
            int a = t[0], b = t[1], c = t[2];
            bal.put(a, bal.getOrDefault(a, 0)-c);
            bal.put(b, bal.getOrDefault(b, 0)+c);
        }

        return settle(new ArrayList<>(bal.values()), 0);
    }

    int settle(List<Integer> list, int start){
        while(start<list.size() && list.get(start) == 0) start++;
        if(start==list.size()) return 0;
        int r = Integer.MAX_VALUE;
        for(int i=start+1; i<list.size(); ++i){
 
            if(list.get(start)*list.get(i)<0){
                list.set(i, list.get(i)+list.get(start));
                r = Math.min(r, 1+settle(list, start+1));
                list.set(i, list.get(i)-list.get(start));
            }
        }

        return r;
    }
}

Friday, August 23, 2019

LeetCode [767] Reorganize String

767. Reorganize String
Medium
Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.
If possible, output any possible result.  If not possible, return the empty string.
Example 1:
Input: S = "aab"
Output: "aba"
Example 2:
Input: S = "aaab"
Output: ""
Note:
  • S will consist of lowercase letters and have length in range [1, 500].
 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
class Solution {
    static bool comp(const pair<char, int>& p1, const pair<char, int>& p2){
        return p1.second>p2.second;
    }
public:
    string reorganizeString(string S) {
        map<char, int> mp;
        int maxCount = 0, sz = S.size();
        char c0;//char with greatest count
        for(auto c:S){
            if(++mp[c]>maxCount){
                maxCount = mp[c];
                c0 = c;
            }
        }
        if(maxCount>ceil(sz/2.0)) return "";
        
        vector<pair<char, int>> chars(mp.begin(), mp.end());
        sort(chars.begin(), chars.end(), comp);
        
        auto it = chars.begin();
        string ret(sz, ' ');
        for(int start = 0; start<=1; start++)
        {
            for(int i=start; i<sz; i+=2){
                if(it->second==0) advance(it, 1);
                ret[i] = it->first;
                it->second--;
            }
        }
        return ret;
    }
};

 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
class Solution {
    public String reorganizeString(String S) {
        int[] count = new int[26];
        for(char c : S.toCharArray()){
            count[c-'a']++;
        }

        int charMax = 0;
        int countMax = 0;
        for(int i=0; i<26; ++i){
            if(count[i]>countMax){
                countMax = count[i];
                charMax = i;
            }
        }
        if(countMax>(S.length()+1)/2) return "";

        char[] res = new char[S.length()];
        int index = 0;
        while(count[charMax]>0){
            res[index] = (char)(charMax+'a');
            index+=2;
            count[charMax]--;
        }

        for(int i=0; i<26; ++i){
            while(count[i]>0){
                if(index>=S.length()) index = 1;
                res[index] = (char)(i+'a');
                index += 2;
                count[i]--;
            }
        }

        return String.valueOf(res);
    }
}

第四轮,白人小哥,刷题网没刷到过(有认出来的请评论下),给一堆学生的id和国籍,如果让他们排队站,如何尽可能的不让两个或者以上的相同国籍的学生站一起。比如有5个国家C的学生和1个国家X的学生, 那CCCCXC的站法比CCCXCC的站法好, 因为后者5个国家C的学生身边都有自己国家的同学,前者只有4个国家C的学生身边有自己国家的同学。 一开始想的的是先按国家sort一遍,隔一个位置放一个人直到填满,后来试了个test case发现不行,改成先把有几个国家用set记录下来,然后while loop一直遍历这个set,逐个放对应的学生,如果没有这个国家的学生了就把国家从set里删除。 最后说了下时间空间复杂度,测了几个test case都ok,不知道是不是最优解。。

第四轮的隔开放学生我面完也没get到,感觉像是找基础的规律之类的数学题吧

第四轮和767那题不一样的是assume input一定有一个解,比如 input: aaab -> output: aaba

第四题,感觉类似lc 旗留旗;用priorityqueue来储存每个国家的count;从大到小,每次poll两个出来,这样alternative placement

Wednesday, August 21, 2019

LeetCode [642] Design Search Autocomplete System

642. Design Search Autocomplete System
Hard
Design a search autocomplete system for a search engine. Users may input a sentence (at least one word and end with a special character '#'). For each character they type except '#', you need to return the top 3 historical hot sentences that have prefix the same as the part of sentence already typed. Here are the specific rules:
  1. The hot degree for a sentence is defined as the number of times a user typed the exactly same sentence before.
  2. The returned top 3 hot sentences should be sorted by hot degree (The first is the hottest one). If several sentences have the same degree of hot, you need to use ASCII-code order (smaller one appears first).
  3. If less than 3 hot sentences exist, then just return as many as you can.
  4. When the input is a special character, it means the sentence ends, and in this case, you need to return an empty list.
Your job is to implement the following functions:
The constructor function:
AutocompleteSystem(String[] sentences, int[] times): This is the constructor. The input is historical dataSentences is a string array consists of previously typed sentences. Times is the corresponding times a sentence has been typed. Your system should record these historical data.
Now, the user wants to input a new sentence. The following function will provide the next character the user types:
List<String> input(char c): The input c is the next character typed by the user. The character will only be lower-case letters ('a' to 'z'), blank space (' ') or a special character ('#'). Also, the previously typed sentence should be recorded in your system. The output will be the top 3 historical hot sentences that have prefix the same as the part of sentence already typed.

Example:
Operation: AutocompleteSystem(["i love you", "island","ironman", "i love leetcode"], [5,3,2,2])
The system have already tracked down the following sentences and their corresponding times:
"i love you" : 5 times
"island" : 3 times
"ironman" : 2 times
"i love leetcode" : 2 times
Now, the user begins another search:

Operation: input('i')
Output: ["i love you", "island","i love leetcode"]
Explanation:
There are four sentences that have prefix "i". Among them, "ironman" and "i love leetcode" have same hot degree. Since ' ' has ASCII code 32 and 'r' has ASCII code 114, "i love leetcode" should be in front of "ironman". Also we only need to output top 3 hot sentences, so "ironman" will be ignored.

Operation: input(' ')
Output: ["i love you","i love leetcode"]
Explanation:
There are only two sentences that have prefix "i ".

Operation: input('a')
Output: []
Explanation:
There are no sentences that have prefix "i a".

Operation: input('#')
Output: []
Explanation:
The user finished the input, the sentence "i a" should be saved as a historical sentence in system. And the following input will be counted as a new search.

Note:
  1. The input sentence will always start with a letter and end with '#', and only one blank space will exist between two words.
  2. The number of complete sentences that to be searched won't exceed 100. The length of each sentence including those in the historical data won't exceed 100.
  3. Please use double-quote instead of single-quote when you write test cases even for a character input.
  4. Please remember to RESET your class variables declared in class AutocompleteSystem, as static/class variables are persisted across multiple test cases. Please see here for more details.
 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
typedef pair<int, string> MYPAIR;

class TrieNode{
public:
    bool isEnd;
    int times;
    vector<TrieNode*> children;
    TrieNode():isEnd(false), times(0){children.resize(256);}
};

class AutocompleteSystem {
    struct comp{
        bool operator()(MYPAIR& p1, MYPAIR& p2){
            if(p1.first==p2.first) return p1.second<p2.second;
            else return p1.first>p2.first;
        }
    };
    TrieNode* root;
    TrieNode* ptr;//current position for input
    string curstr;//current string for input
    
    void insert(string s, int t = -1){
        TrieNode* p = root;
        for(auto c:s){
            if(p->children[c]==NULL){
                p->children[c] = new TrieNode();
            }
            p = p->children[c];
        }
        p->isEnd = true;
        p->times += t<0?1:t;
    }
    
    void search(priority_queue<MYPAIR, vector<MYPAIR>, comp> &pq, TrieNode *p, string str){
        if(p->isEnd){
            pq.push(make_pair(p->times, str));
            if(pq.size()>3) pq.pop();
        }
        for(int i=0; i<256; ++i){
            if(p->children[i]!=NULL) 
                search(pq, p->children[i], str+char(i));
        }
    }
public:
    AutocompleteSystem(vector<string>& sentences, vector<int>& times) {
        root = new TrieNode();
        for(int i=0; i<sentences.size(); ++i){
            insert(sentences[i], times[i]);
        }
        ptr = root;
        curstr = "";
    }
    
    vector<string> input(char c) {
        vector<string> ret;
        if(c=='#'){
            insert(curstr);
            curstr = "";
            ptr = root;
        }else if(ptr==NULL || ptr->children[c]==NULL){
            ptr->children[c] = new TrieNode();
            ptr = ptr->children[c];
            curstr += c;
        }else{
            priority_queue<MYPAIR, vector<MYPAIR>, comp> pq;
            ptr = ptr->children[c];
            curstr += c;
            search(pq, ptr, curstr);
                ret.insert(ret.begin(), pq.top().second);
                pq.pop();
            }
        }
        
        return ret;
    }
};

/**
 * Your AutocompleteSystem object will be instantiated and called as such:
 * AutocompleteSystem* obj = new AutocompleteSystem(sentences, times);
 * vector<string> param_1 = obj->input(c);
 */

 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
class AutocompleteSystem {
    class TrieNode{
        boolean isEnd;
        TrieNode[] children;
        int hot;
        TrieNode(){
            isEnd = false;
            children = new TrieNode[256];
            hot = 0;
        }
    }
    TrieNode root;
    TrieNode ptr;
    String cur = "";

    public AutocompleteSystem(String[] sentences, int[] times) {
        root = new TrieNode();
        ptr = root;
        int n = sentences.length;
        for(int i=0; i<n; ++i){
            build(sentences[i], times[i]);
        }
    }

    void build(String str, int time){
        TrieNode p = root;
        for(char c : str.toCharArray()){
            int i = (int)c;
            if(p.children[i]==null){
                p.children[i] = new TrieNode();
            }
            p = p.children[i];
        }
        p.isEnd = true;
        p.hot += time;
    }
    
    void search(TrieNode p, String s, PriorityQueue<Map.Entry<String, Integer>> pq){
        if(p.isEnd){
            pq.add(Map.entry(s, p.hot));
            if(pq.size()>3) pq.poll();
        }
        for(int i=0; i<256; ++i){
            if(p.children[i]!=null){
                search(p.children[i], s+(char)i, pq);
            }
        }
    }

    public List<String> input(char c) {
        if(c!='#' && ptr.children[(int)c]!=null){
            PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<>((a, b)->{
                if(a.getValue()==b.getValue()) return b.getKey().compareTo(a.getKey());
                else return a.getValue()-b.getValue();
            });
            search(ptr.children[(int)c], cur+c, pq);
            List<String> list = new ArrayList<>();
            while(!pq.isEmpty()){
                list.add(0, pq.poll().getKey());
            }
            cur += c;
            ptr = ptr.children[(int)c];
            return list;
        }else if(c=='#'){
            build(cur, 1);
            cur = "";
            ptr = root;
        }else{//is null
            ptr.children[(int)c] = new TrieNode();
            ptr = ptr.children[(int)c];
            cur += c;
        }
        return new ArrayList<>();
    }
}