-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 1160_Find_Words_That_Can_Be_Formed_by_Characters.java
- Loading branch information
Showing
1 changed file
with
36 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
// id: 1160 | ||
// Name: Find Words That Can Be Formed by Characters | ||
// link: https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/ | ||
// Difficulty: Easy | ||
|
||
class Solution { | ||
int [] map = new int[26]; | ||
int [] wordMap; | ||
public int countCharacters(String[] words, String chars) { | ||
for (int i = 0; i < chars.length(); i++) { | ||
map[chars.charAt(i)-'a']++; | ||
} | ||
|
||
int result = 0; | ||
for (String word: words) { | ||
if (matches(word)) { | ||
result += word.length(); | ||
} | ||
} | ||
|
||
|
||
return result; | ||
} | ||
|
||
private boolean matches (String word) { | ||
wordMap = new int[26]; | ||
|
||
for (int i = 0; i < word.length(); i++) { | ||
int c = word.charAt(i) - 'a'; | ||
wordMap[c]++; | ||
if (wordMap[c]>map[c]) return false; | ||
} | ||
|
||
return true; | ||
} | ||
} |