[LeetCode] Occurrences After Bigram

아르당·2026년 3월 31일

LeetCode

목록 보기
233/303
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

두 문자열 first와 second가 주어졌을 때, second가 첫 번째 바로 다음에 오고, third가 두 번째 바로 다음에 오는 "first second third"와 같은 형식이 나타나는 경우를 생각해라.
각 "first second third"에 나타나는 모든 단어 third의 배열을 반환해라.

Example

#1
Input: text = "alice is a good girl she is a good student", first = "a", second = "good"
Output: ["girl", "student"]

#2
Input: text = "we will we will rock you", first = "we", second = "will"
Output: ["we", "rock"]

Constraints

  • 1 <= text.length <= 1000
  • text는 영어 소문자와 여백으로 구성된다.
  • text의 모든 단어는 단일 여백으로 구분된다.
  • 1 <= first.length, second.length <= 10
  • first와 second는 영어 소문자로 구성된다.
  • text는 처음과 끝에 여백을 가지지 않는다.

Solved

class Solution {
    public String[] findOcurrences(String text, String first, String second) {
        String[] words = text.split(" ");
        List<String> result = new ArrayList<>();

        for(int i = 0; i < words.length - 2; i++){
            if(words[i].equals(first) && words[i + 1].equals(second)){
                result.add(words[i + 2]);
            }
        }

        return result.toArray(new String[0]);
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글