Showing posts with label string. Show all posts
Showing posts with label string. Show all posts

Sunday, August 30, 2015

LeetCode [273] Integer to English Words

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.
Example 1:
Input: 123
Output: "One Hundred Twenty Three"
Example 2:
Input: 12345
Output: "Twelve Thousand Three Hundred Forty Five"
Example 3:
Input: 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
Example 4:
Input: 1234567891
Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
 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 {
    vector<string> lessThan20, tens, thousands;
public:
    string numberToWords(int num) {
        if(num==0) return "Zero";
        lessThan20 = vector<string>{"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
        tens = vector<string>{"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
        string ret = helper(num);
        string s;
        for(int i=0; i<ret.size(); ++i)
        {
            if((i>0 && ret[i]==' ' && ret[i-1]==' ') || (i==ret.size()-1 && ret[i]==' ')) continue;
            else s += ret[i];
        }
        return s;
    }

    string helper(int num)
    {
        if(num < 20) return lessThan20[num];
        else if(num<100){
            return tens[num/10] + " " + helper(num%10);
        }else if(num<1000)
        {
            return lessThan20[num/100] + " " + "Hundred" + " " + helper(num%100);
        }else if(num<1000000)
        {
            return helper(num/1000) + " " + "Thousand" + " " + helper(num%1000);
        }else if(num<1000000000)
        {
            return helper(num/1000000) + " " + "Million" + " " + helper(num%1000000);
        }else
        {
            return helper(num/1000000000) + " " + "Billion" + " " + helper(num%1000000000);
        }
    }
};

 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
class Solution {
    Map<Integer, String> map = new HashMap<>();
    public String numberToWords(int num) {
        map.put(0, "Zero");
        map.put(1, "One");
        map.put(2, "Two");
        map.put(3, "Three");
        map.put(4, "Four");
        map.put(5, "Five");
        map.put(6, "Six");
        map.put(7, "Seven");
        map.put(8, "Eight");
        map.put(9, "Nine");
        map.put(10, "Ten");
        map.put(11, "Eleven");
        map.put(12, "Twelve");
        map.put(13, "Thirteen");
        map.put(14, "Fourteen");
        map.put(15, "Fifteen");
        map.put(16, "Sixteen");
        map.put(17, "Seventeen");
        map.put(18, "Eighteen");
        map.put(19, "Nineteen");
        map.put(20, "Twenty");
        map.put(30, "Thirty");
        map.put(40, "Forty");
        map.put(50, "Fifty");
        map.put(60, "Sixty");
        map.put(70, "Seventy");
        map.put(80, "Eighty");
        map.put(90, "Ninety");
        map.put(100, "Hundred");
        map.put(1000, "Thousand");
        map.put(1000000, "Million");
        map.put(1000000000, "Billion");

        return helper(num);
    }

    String toString(int gra, int num){
        int cnt = num/gra;
        String s = helper(cnt) + " " + map.get(gra) ;
        int r = num%gra;
        if(r>0) s += " " + helper(r);
        return s;
    }

    String helper(int num){
        String s = "";
        if(num<=20) return map.get(num);
        else if(num<100){//(20, 100)
            int r = num%10;
            s = map.get(num-r);
            if(r>0) s += " " + helper(r);
            return s;
        }else if(num<1000){//[10 , 1000)
            s = toString(100, num);
        }else if(num<1000000){//[1000, 1000000)
            s = toString(1000, num);
        }else if(num<1000000000){//[1000000, 1000000000)
            s = toString(1000000, num);
        }else{//[1000000000, 
            s = toString(1000000000, num);
        }
        return s;
    }
}

Saturday, August 29, 2015

MJ [30] Longest Words in a Dictionary

Question:
Find the longest words in a dictionary of legal words that can be constructed from a given list of letters. The dictionary is give by ospd.txt.
$ ./test ospd.txt i g h l p r a
ret     :argil glair grail graph hilar laigh phial pilar ralph
ret_trie:argil glair grail graph hilar laigh phial pilar ralph


Ref

Friday, August 28, 2015

LeetCode [271] Encode and Decode Strings

 271. Encode and Decode Strings

Medium

Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.

Machine 1 (sender) has the function:

string encode(vector<string> strs) {
  // ... your code
  return encoded_string;
}
Machine 2 (receiver) has the function:
vector<string> decode(string s) {
  //... your code
  return strs;
}

So Machine 1 does:

string encoded_string = encode(strs);

and Machine 2 does:

vector<string> strs2 = decode(encoded_string);

strs2 in Machine 2 should be the same as strs in Machine 1.

Implement the encode and decode methods.

 

Note:

  • The string may contain any possible characters out of 256 valid ascii characters. Your algorithm should be generalized enough to work on any possible characters.
  • Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.
  • Do not rely on any library method such as eval or serialize methods. You should implement your own encode/decode algorithm.
 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
//C++: 92ms
typedef unsigned char uchar;

class Codec {
public:

    // Encodes a list of strings to a single string.
    string encode(vector<string>& strs) {
        string ret;
        for(auto s:strs){
            int i = 0, len = s.size(), cnt;
            while(i<len){
                cnt = 1;
                uchar c = s[i++];
                while(i<len && (uchar)s[i]==c && cnt<254){
                    i++; cnt++;
                }
                ret += (uchar)cnt;
                ret += c;
            }
            ret += (uchar)255;
        }
        return ret;
    }

    // Decodes a single string to a list of strings.
    vector<string> decode(string s) {
        vector<string> ret;
        string cur;
        int i=0, len = s.size();
        while(i<len){
            uchar c = s[i++];
            if(c==(uchar)255){
                ret.push_back(cur);
                cur.clear();
            }else{
                int cnt = c;
                c = s[i++];
                for(int i=0; i<cnt; ++i) cur += c;
            }
        }
        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
public class Codec {
	// Encodes a list of strings to a single string.
    public String encode(List<String> strs) {
        StringBuilder sb = new StringBuilder();
        for(String s : strs) {
            sb.append(s.length()).append('/').append(s);
        }
        return sb.toString();
    }

    // Decodes a single string to a list of strings.
    public List<String> decode(String s) {
        List<String> ret = new ArrayList<String>();
        int i = 0;
        while(i < s.length()) {
            int slash = s.indexOf('/', i);
            int size = Integer.valueOf(s.substring(i, slash));
            i = slash + size + 1;
            ret.add(s.substring(slash + 1, i));
        }
        return ret;
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(strs));

Wednesday, August 5, 2015

LeetCode [249] Group Shifted Strings

 249. Group Shifted Strings

Medium

Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence:

"abc" -> "bcd" -> ... -> "xyz"

Given a list of non-empty strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence.

Example:

Input: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"],
Output: 
[
  ["abc","bcd","xyz"],
  ["az","ba"],
  ["acef"],
  ["a","z"]
]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
    public List<List<String>> groupStrings(String[] strings) {
        Map<String, List<String>> groups = new HashMap<>();
        for(String str : strings){
            StringBuilder sb = new StringBuilder();
            int diff = str.charAt(0) - 'a';
            for(char c : str.toCharArray()){
                sb.append((char)(c-diff>=97?c-diff:c-diff+26));
            }
            groups.computeIfAbsent(sb.toString(), k->new ArrayList<>()).add(str);
        }
        
        List<List<String>> lists = new ArrayList<>();
        for(List<String> list : groups.values()){
            lists.add(list);
        }
        
        return lists;
    }
}

Friday, April 10, 2015

LeetCode [186] Reverse Words in a String II

===================

Ref
[1] https://leetcode.com/problems/reverse-words-in-a-string-ii/
OJ

LeetCode [165] Compare Version Numbers

 165. Compare Version Numbers

Medium

Given two version numbers, version1 and version2, compare them.

    Version numbers consist of one or more revisions joined by a dot '.'. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example 2.5.33 and 0.1 are valid version numbers.

    To compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. This means that revisions 1 and 001 are considered equal. If a version number does not specify a revision at an index, then treat the revision as 0. For example, version 1.0 is less than version 1.1 because their revision 0s are the same, but their revision 1s are 0 and 1 respectively, and 0 < 1.

    Return the following:

    • If version1 < version2, return -1.
    • If version1 > version2, return 1.
    • Otherwise, return 0.

     

    Example 1:

    Input: version1 = "1.01", version2 = "1.001"
    Output: 0
    Explanation: Ignoring leading zeroes, both "01" and "001" represent the same integer "1".
    

    Example 2:

    Input: version1 = "1.0", version2 = "1.0.0"
    Output: 0
    Explanation: version1 does not specify revision 2, which means it is treated as "0".
    

    Example 3:

    Input: version1 = "0.1", version2 = "1.1"
    Output: -1
    Explanation: version1's revision 0 is "0", while version2's revision 0 is "1". 0 < 1, so version1 < version2.
    

    Example 4:

    Input: version1 = "1.0.1", version2 = "1"
    Output: 1
    

    Example 5:

    Input: version1 = "7.5.2.4", version2 = "7.5.3"
    Output: -1
    

     

    Constraints:

    • 1 <= version1.length, version2.length <= 500
    • version1 and version2 only contain digits and '.'.
    • version1 and version2 are valid version numbers.
    • All the given revisions in version1 and version2 can be stored in a 32-bit integer.
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    class Solution {
    public:
        int compareVersion(string version1, string version2) {
            int n1 = version1.size(), n2 = version2.size(), i1 = 0, i2 = 0, v1 = 0, v2 = 0;
            while(i1<n1 && i2<n2){
                int j1 = i1, j2 = i2;
                while(j1<n1 && version1[j1]!='.') j1++;
                while(j2<n2 && version2[j2]!='.') j2++;
                v1 = stoi(version1.substr(i1, j1-i1));
                v2 = stoi(version2.substr(i2, j2-i2));
                if(v1>v2) return 1;
                else if(v1<v2) return -1;
                i1 = j1+1;
                i2 = j2+1;
            }
            v1 = 0;
            v2 = 0;
            if(i1<n1) v1 = stoi(version1.substr(i1, n1-i1));
            if(i2<n2) v2 = stoi(version2.substr(i2, n2-i2));
            if(v1>v2) return 1;
            else if(v1==v2) return 0;
            else return -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 {
        boolean hasPositive(String str){
            for(int i=0; i<str.length(); ++i){
                if(str.charAt(i)!='.' && str.charAt(i)!='0') return true;
            }
            return false;
        }
    
        public int compareVersion(String version1, String version2) {
            int n1 = version1.length(), n2 = version2.length();
            int i1 = 0, i2 = 0;
            while(i1<n1 && i2<n2){
                int e1 = version1.indexOf('.', i1);
                int e2 = version2.indexOf('.', i2);
                if(e1==-1) e1 = n1;
                if(e2==-1) e2 = n2;
                int v1 = Integer.parseInt(version1.substring(i1, e1));
                int v2 = Integer.parseInt(version2.substring(i2, e2));
                if(v1>v2) return 1;
                if(v1<v2) return -1;
                i1 = e1+1;
                i2 = e2+1;
            }
    
            if(i1<n1 && hasPositive(version1.substring(i1))) return 1;
            if(i2<n2 && hasPositive(version2.substring(i2))) return -1;
            return 0;
        }
    }
    

     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
    class Solution {
        int compareString(String v1, String v2){
            int i1 = v1.equals("")?0:Integer.parseInt(v1);
            int i2 = v2.equals("")?0:Integer.parseInt(v2);
            if(i1<i2) return -1;
            else if(i1==i2) return 0;
            else return 1;
        }
        public int compareVersion(String version1, String version2) {
            int i = 0, j = 0;
            while(i<version1.length() || j<version2.length()){
                int dotIndex1 = version1.indexOf('.', i);
                String ver1 = version1.substring(i, dotIndex1==-1?version1.length():dotIndex1);
    
                int dotIndex2 = version2.indexOf('.', j);
                String ver2 = version2.substring(j, dotIndex2==-1?version2.length():dotIndex2);
    
                int r = compareString(ver1, ver2);
                if(r!=0) return r;
                
                i = dotIndex1<0?version1.length():dotIndex1+1;
                j = dotIndex2<0?version2.length():dotIndex2+1;
            }
    
            return 0;
        }
    }
    

     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 int compareVersion(String version1, String version2) {
            String[] list1 = version1.split("\\.");
            String[] list2 = version2.split("\\.");
            int n1 = list1.length, n2 = list2.length;
            int i = 0, j = 0;
            while(i<n1 && j<n2){
                String v1 = trim(list1[i]);
                String v2 = trim(list2[i]);
                int r = value(v1)-value(v2);
                if(r<0) return -1;
                else if(r>0) return 1;
                i++;
                j++;
            }
    
            while(i<n1 && trim(list1[i]).length()==0) i++;
            while(j<n2 && trim(list2[j]).length()==0) j++;
    
            if(i==n1 && j==n2) return 0;
            if(i<n1) return 1;
            return -1;
        }
    
        String trim(String s){
            int i = 0;
            while(i<s.length() && s.charAt(i)=='0') i++;
            return s.substring(i);
        }
        
        int value(String s){
            if(s.length()==0) return 0;
            else return Integer.valueOf(s);
        }
    }