ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 99클럽(2기) - 코테스터디 19일차 TIL # 완전 탐색
    Algorithm 2024. 6. 17. 05:54

    LeetCode - 2942. Find Words Containing Character

    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.


     

    1. 첫 번째 풀이

     리스트 컴프리핸션을 이용해 한 줄로 풀었다. enumerate 함수를 사용해서 words의 인덱스 idx와 요소 word를 반복문으로 순회하며 x가 word 안에 포함되어 있으면 해당 인덱스를 추가한 리스트를 반환한다. 

    from typing import List
    class Solution:
        def findWordsContaining(self, words: List[str], x: str) -> List[int]:
            return [idx for idx, word in enumerate(words) if x in word]

     

     

    2. 두 번째 풀이

     자바로 풀어봤다.

     

    1) 결과를 저장할 indices 리스트 초기화

     

    2) 0부터 words.size()까지 순회

     for 루프를 사용하여 words를 순회하면서 단어에 문자 x가 포함되어 있는지 검사한다. 만약 포함되어 있으면 해당 인덱스를 indices 리스트에 추가한다.

     

    3) indices 리스트 반환

    import java.util.ArrayList;
    import java.util.List;
    
    public class FindWordsWithChar {
    	public List<Integer> findWordsWithChar(String[] words, char x) {
            List<Integer> indices = new ArrayList<>();
            for (int i = 0; i < words.length; i++) {
                if (words[i].indexOf(x) != -1) {
                    indices.add(i);
                }
            }
            return indices;
        }
    }

     

     

    3. 세 번째 풀이

     역시 자바로 풀었으며, 스트림을 사용했다.

     

    1) 정수 스트림 생성

     IntStream.range 함수를 이용해 0부터 words.length까지의 정수 스트림을 생성한다. 

     

    2) 각 요소가 문자 x를 포함하는지 확인

     filter 함수를 이용해 각 인덱스 i에 대해서 words[i]가 문자  x를 포함하는지 확인한다.

     

    3) IntStream 변환 

     원시 타입 int 스트림을 Integer 객체 스트림으로 변환한다.

     

    4) 스트림의 결과를 리스트로 수집

     collect(Collectors.toList())로 스트림한 결과를 리스트로 수집한다.  

    import java.util.ArrayList;
    import java.util.List;
    import java.util.stream.Collectors;
    import java.util.stream.IntStream;
    
    class Solution {
        public List<Integer> findWordsContaining(String[] words, char x) {
            return IntStream.range(0, words.length)
                    .filter(i -> words[i].indexOf(x) != -1)
                    .boxed()
                    .collect(Collectors.toList());
        }
    }

     

     

    4. 느낀점

     여유가 없어서 항상 파이썬으로만 풀었는데 오늘 문제가 쉬워서 자바로도 풀어봤다. 앞으로도 자바 풀이도 함께 해야겠다. 

    댓글

Designed by Tistory.