一、問題鏈接:
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表示的字符串
