[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.

  • 問題:判斷前面數(shù)組中的字符串能否由后面的字符組成,假如可以,則將組成的字符串的長度累加

二、思路:

1、遍歷一維數(shù)組,取出一個又一個的字符串
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
    • 原方法如下:實際調(diào)用的是indexof方法,至于indexof的話,則返回指定字符串在當前字符串對象中的最后一次出現(xiàn)的索引位置


      contains方法

3、replaceFirst:根據(jù)給定的正則表達式替換當前字符串匹配到的第一個子字符串為參數(shù)replacement表示的字符串

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1160. 拼寫單詞 https://leetcode-cn.com/classic/problems/find-...
    z761943閱讀 543評論 0 2
  • 第5章 引用類型(返回首頁) 本章內(nèi)容 使用對象 創(chuàng)建并操作數(shù)組 理解基本的JavaScript類型 使用基本類型...
    大學(xué)一百閱讀 3,679評論 0 4
  • 官網(wǎng) 中文版本 好的網(wǎng)站 Content-type: text/htmlBASH Section: User ...
    不排版閱讀 4,714評論 0 5
  • package cn.itcast_01;/* 字符串:就是由多個字符組成的一串數(shù)據(jù)。也可以看成是一個字符數(shù)組。 ...
    蛋炒飯_By閱讀 725評論 0 0
  • 4.7. Text Sequence Type — str Python中的文本數(shù)據(jù)由str對象或strings處...
    xpf2000閱讀 3,411評論 0 2

友情鏈接更多精彩內(nèi)容