[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的话,则返回指定字符串在当前字符串对象中的最后一次出现的索引位置


      contains方法

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1160. 拼写单词 https://leetcode-cn.com/classic/problems/find-...
    z761943阅读 3,408评论 0 2
  • 第5章 引用类型(返回首页) 本章内容 使用对象 创建并操作数组 理解基本的JavaScript类型 使用基本类型...
    大学一百阅读 8,472评论 0 4
  • 官网 中文版本 好的网站 Content-type: text/htmlBASH Section: User ...
    不排版阅读 9,955评论 0 5
  • package cn.itcast_01;/* 字符串:就是由多个字符组成的一串数据。也可以看成是一个字符数组。 ...
    蛋炒饭_By阅读 3,800评论 0 0
  • 4.7. Text Sequence Type — str Python中的文本数据由str对象或strings处...
    xpf2000阅读 8,529评论 0 2