LeetCode.1160- can find the string by the given characters (Find Words That Can Be Formed by Characters)

This is the first Ogawa 411 update, the first 443 Pian original

Look problems and prepare

Introduced today is LeetCode algorithm in title Easy level of 262 questions (overall title number is 1160 ). You'll get a string array of words and a string chars. If the character string may be composed of characters (each character only once), the string is good. Returns the length of the strings and all good.

E.g:

Input: words = [ "cat", "bt", "hat", "tree"], chars = "atach"
Output: 6
Description: The character string may be formed of "cat" and "hat", and therefore the answer is 3 + 3 = 6.

Input: words = [ "hello", "world", "leetcode"], chars = "welldonehoneyr"
Output: 10
Description: The character string may be formed of "hello" and "world", so the answer is 5 + 5 = 10 .

Note :

  • 1 <= words.length <= 1000

  • 1 <= words[i].length , chars.length <= 100

  • All string contains only lowercase letters.

The first solution

Title mean, given a string of lowercase letters chars, in the string array words, if the word can be made charsin the composition of the characters, then the word is a good word.

We can direct translation of the subject, will charsbe understood to a dictionary array, count the number of each letter appears, into a 26-bit length of intthe array, then to traverse wordsin a word, using the same principle, as the word dictionary for each letter array index occurs once minus 1, if the dictionary array element value is less than 0, can not be described by the current word charsin the letters, this end of the cycle, until all words been traversed.

public int countCharacters(String[] words, String chars) {
    // 获取字典数组
    int[] dict = stringToIntegerArray(chars);
    int sum = 0;
    for (int i=0, len=words.length; i<len; i++) {
        // 复制一份字典数组,为后面的减法做准备
        int[] temp = dict.clone();
        int len2 = words[i].length();
        // 默认当前单词是好字符串
        boolean flag = true;
        for (int j=0; j<len2; j++) {
            // 单词中的字母不在字典中,或超过使用次数
            if (--temp[words[i].charAt(j)-'a'] < 0) {
                flag = false;
                break;
            }
        }
        if (flag) {
            sum += words[i].length();
        }
    }
    return sum;
}

/**
 * 将字符串转为长度为26的int数组
 * @param s 字符串
 * @return 长度为26的int数组
 */
public int[] stringToIntegerArray(String s) {
    int[] arr = new int[26];
    for (int i=0, len=s.length(); i<len; i++) {
        arr[s.charAt(i)-'a']++;
    }
    return arr;
}


The second solution

The first solution and the idea is similar, except that the first solution is to copy the array replaced with another kind of writing, the current word will be converted to a length of 26 of intthe array, and then compare the size of the array and the array element values dictionary word some letters, if the word element of the array current value is greater than the current dictionary array element value, it indicates that the word is not in the dictionary or exceeded the number of occurrences in the dictionary.

public int countCharacters2(String[] words, String chars) {
    // 获取字典数组
    int[] dict = stringToIntegerArray(chars);
    int sum = 0, len = words.length, len2 = dict.length;
    for (int i=0; i<len; i++) {
        // 将单词也转为int数组
        int[] temp = stringToIntegerArray(words[i]);
        boolean flag = true;
        for (int j=0; j<len2; j++) {
            if (temp[j] > dict[j]) {
                flag = false;
                break;
            }
        }
        if (flag) {
            sum += words[i].length();
        }
    }
    return sum;
}

/**
 * 将字符串转为长度为26的int数组
 * @param s 字符串
 * @return 长度为26的int数组
 */
public int[] stringToIntegerArray(String s) {
    int[] arr = new int[26];
    for (int i=0, len=s.length(); i<len; i++) {
        arr[s.charAt(i)-'a']++;
    }
    return arr;
}


summary

Thematic algorithm has now updated LeetCode algorithm of feature articles 268 + articles, public Number dialog box reply [ data structures and algorithms ], [ algorithm ], [ data structures Any words] in obtaining a series of articles collection.

That's all, if you have any good solution ideas, suggestions or other issues, you can exchange comments below, thumbs up, message forwarding and support is the greatest reward for me!

Guess you like

Origin www.cnblogs.com/xiaochuan94/p/11566270.html