题目描述
1078. Bigram 分词
题解
此题是一道简单的字符串匹配题,遍历text字符串,当 first 和 second 都符合条件则添加后一个字符串
代码参考:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { public String[] findOcurrences(String text, String first, String second) { if (text == null || text.length() == 0 || first == null || second == null || first.length() == 0 || second.length() == 0) { return new String[0]; } String[] textArray = text.split(" "); if (textArray.length < 3) { return new String[0]; } List<String> res = new ArrayList<>(); for (int i = 0; i + 2 < textArray.length; i++) { if (textArray[i].equals(first) && textArray[i + 1].equals(second)) { res.add(textArray[i + 2]); } } return res.toArray(new String[res.size()]); } }
|