LeetCode 1078. Bigram word

Given the first word firstand the second word second, consider some text textpossible in the "first second third"case of the form, which secondimmediately firstappears thirdimmediately secondappears.

For each such case, the third word "third"is added to the answers, and return the answer.

Example 1:

输入:text = “alice is a good girl she is a good student”, first = “a”,
second = “good”
输出:[“girl”,“student”]

Example 2:

输入:text = “we will we will rock you”, first = “we”, second = “will”
输出:[“we”,“rock”]

Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/occurrences-after-bigram
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

solution

public class Solution {

   public String[] findOcurrences(String text, String first, String second) {
        String[] s = text.split(" ");
        String str = "";
        for (int i = 0; i < s.length - 2; i++) {
            if (s[i].equals(first) && s[i + 1].equals(second)) {
                str += s[i + 2] + " ";
            }
        }
        return str.split(" ");
    }
}

However, this output will be written when there is no one more qualified string quotes, use list to save:

class Solution {
    public String[] findOcurrences(String text, String first, String second) {
        String[] s = text.split(" ");
        List<String> list = new ArrayList();
        for (int i = 0; i < s.length - 2; i++) {
            if (s[i].equals(first)&&s[i+1].equals(second)){
                list.add(s[i+2]);
            }
        }
        String[] strings=new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            strings[i]=list.get(i);
        }
        return strings;
    }
}

Thinking

  1. The text is converted to an array of strings
  2. Traversal to find all consecutive first and second, third save
Released seven original articles · won praise 2 · Views 218

Guess you like

Origin blog.csdn.net/qq_44000076/article/details/98483000
Recommended