[Leetcode-java] 1160. Find Words That Can Be Formed by Characters

一、问题链接:

https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/
Example 1:

Input: words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6
Explanation:
The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.

  • 问题:判断前面数组中的字符串能否由后面的字符组成,假如可以,则将组成的字符串的长度累加

二、思路:

1、遍历一维数组,取出一个又一个的字符串
2、再遍历每个String中的字符,看chars是否包含
3、注意点:假如chars包含到了,则需要移除改元素

三、编码

class Solution {
    public int countCharacters(String[] words, String chars) {
      int total = 0;
        for (int i = 0; i < words.length; i++) {
            String a = words[i];
            if (a == null || a == "") {
                continue;
            }
            String[] temp = a.split("");
            int len = 0;
            String tempStr = chars;
            for (int j = 0; j < temp.length; j++) {

                if (tempStr.contains(temp[j])) {
                    len++;
                    tempStr = tempStr.replaceFirst(temp[j],"");
                }
            }
            if (len == temp.length) {
                total += len;
            }
        }
        return total;
        
    }
}

知识点:使用了String的三个API接口

  • 1、split:按照regex进行字符分割,limit表示分割成几部分
  • 2、contains:当且仅当当前字符串包含指定的字符序列才会返回true
    • 原方法如下:实际调用的是indexof方法,至于indexof的话,则返回指定字符串在当前字符串对象中的最后一次出现的索引位置


      [Leetcode-java] 1160. Find Words That Can Be Formed by Characters_第1张图片
      contains方法

3、replaceFirst:根据给定的正则表达式替换当前字符串匹配到的第一个子字符串为参数replacement表示的字符串

你可能感兴趣的:([Leetcode-java] 1160. Find Words That Can Be Formed by Characters)