Occurrences After Bigram

Occurrences After Bigram

Given two strings first and second, consider occurrences in some text of the form "first second third", where second comes immediately after first, and third comes immediately after second.

Return an array of all the words third for each occurrence of "first second third".

LeetCode Problem - 1078

class Solution {
    String first, second, text;
    String[] splitText;

    public String[] findOcurrences(String text, String first, String second) {
        // Initialize a list to store the result
        List<String> list = new ArrayList<>();

        // Store the input parameters for later use
        this.first = first;
        this.second = second;
        this.text = text;

        // Split the input text into words based on spaces
        String[] splitText = text.split(" ");
        this.splitText = splitText; // Save the split text for later comparison

        // Iterate through the words in the split text
        for (int i = 0; i < splitText.length; i++) {
            String str = splitText[i];

            // Check if the current word matches the first word
            if (str.equals(first) && (i != splitText.length - 1)) {
                // Check if the next word matches the second word, and ensure there are at least two more words after
                boolean flag = findThirdString(splitText[i + 1], i + 1);

                // If the second word matches, add the word after it (the third word) to the result list
                if (flag) {
                    list.add(splitText[i + 2]);
                }
            }
        }

        // Convert the list of results to an array and return it
        return list.toArray(new String[0]);
    }

    // Helper function to check if the second word is found after the first
    public boolean findThirdString(String str, int idx) {
        // Check if the word at the current index matches the second word
        String textIdx2 = splitText[idx];

        // Return true if the second word is found and there is at least one word after it
        if (textIdx2.equals(second) && idx != splitText.length - 1) {
            return true;
        }

        // Return false if the second word is not found
        return false;
    }
}

Did you find this article valuable?

Support Perf Insights by becoming a sponsor. Any amount is appreciated!