99 Club 2기 | Java | Beginner
🈶 2942. Find Words Containing Character
🏷 관련 주제 : Array String contains()
Easy
You are given a 0-indexed array of strings words and a character x.
Return an array of indices representing the words that contain the character x.
Note that the returned array may be in any order.
Example 1:
Input: words = ["leet","code"], x = "e"
Output: [0,1]
Explanation: "e" occurs in both words: "leet", and "code". Hence, we return indices 0 and 1.
Example 2:
Input: words = ["abc","bcd","aaaa","cbc"], x = "a"
Output: [0,2]
Explanation: "a" occurs in "abc", and "aaaa". Hence, we return indices 0 and 2.
Example 3:
Input: words = ["abc","bcd","aaaa","cbc"], x = "z"
Output: []
Explanation: "z" does not occur in any of the words. Hence, we return an empty array.
Constraints:
1 <= words.length <= 501 <= words[i].length <= 50xis a lowercase English letter.words[i]consists only of lowercase English letters.
Accepted 120,988 | Submissions 136,740
✔ Solution with contains
import java.util.List;
import java.util.ArrayList;
class Solution {
public List<Integer> findWordsContaining(String[] words, char x) {
List<Integer> answer = new ArrayList<>();
for (int i = 0; i < words.length; i++) {
if (words[i].contains(String.valueOf(x))) {
answer.add(i);
}
}
return answer;
}
}
채점 결과

💥 오늘 만난 문제 & 나의 시도 💦 & 해결 방법 👍
📌 오늘 만난 문제 : 매개변수로 받은 문자열 배열 words 와 character x에 대하여 words의 원소들 중, x를 포함하는 문자열의 인덱스 배열을 반환하시오.
1. 결과값을 반환할 List<Integer> 객체 answer 생성
List<Integer> answer = new ArrayList<>();
2. 0번 인덱스부터 words의 문자열에 x 포함 여부 탐색, x를 포함하면 answer에 해당 문자열의 인덱스 삽입
문자열에 character
x의 포함여부는문자열.contains(String.valueOf(x))를 이용하자.
for (int i = 0; i < words.length; i++) {
if (words[i].contains(String.valueOf(x))) {
answer.add(i);
}
}
3. answer 객체 반환
return answer;
💬 무엇을 새롭게 알았는지
List 객체 생성은 ArrayList로 하자.
문자열에 특정 문자 포함여부는 contains()메서드를 이용할 수 있다.contains()메서드의 매개변수는 character타입 안됨.
포함 여부를 판단할 특정 문자열을 매개변수로 주어야 한다.