코딩테스트 풀이/JAVA
[LeetCode/Easy] 1160. Find Words That Can Be Formed by Characters
무지맘
2023. 4. 6. 01:14
1. Input
1) String[] words
2) String chars
2. Output
1) words의 단어들 중 chars에 있는 알파벳으로 만들 수 있는 단어들의 길이의 합을 반환
- chars에 있는 각 알파벳은 1번씩 사용 가능하다.
- 같은 알파벳이 2개 있다면 그 알파벳은 2번 사용이 가능한 것이다.
3. Constraint
1) 1 <= words.length <= 1000
2) 1 <= words[i].length, chars.length <= 100
3) words의 단어와 chars는 알파벳 소문자로 이루어져 있다.
4. Example
Input: words = ["cat","bt","hat","tree"], chars = "atach" -> Output: 6
설명: chars에 있는 알파벳으로 만들 수 있는 단어는 cat, hat이므로 3+3=6을 반환한다.
5. Code
1) 첫 코드(2023/04/06)
int[] ch = new int[26];
for(int i=0 ; i<chars.length() ; i++)
ch[chars.charAt(i)-'a']++;
int[] wo = new int[26];
int answer = 0;
for(String s : words){
answer += s.length();
for(int i=0 ; i<s.length() ; i++)
wo[s.charAt(i)-'a']++;
for(int i=0 ; i<26 ; i++){
if(wo[i]>ch[i]){
answer -= s.length(); break;
}
}
Arrays.fill(wo,0);
}
return answer;