// 1813. Sentence Similarity III
class Solution {
public boolean areSentencesSimilar(String sentence1, String sentence2) {
String[] words1 = sentence1.split(" ");
String[] words2 = sentence2.split(" ");
int left;
int right;
int shortLength = Math.min(words1.length, words2.length);
for (left = 0; left < shortLength; ++left) {
if (!words1[left].equals(words2[left])) {
break;
}
}
if (left == shortLength) {
return true;
}
for (right = 0; right < shortLength - left; ++right) {
if (!words1[words1.length - 1 - right].equals(words2[words2.length - 1 - right])) {
break;
}
}
return shortLength == left + right;
}
}
学习笔记:
这是一道字符串的题目。
先一波切割,然后比较左边,比较右边。
左右相同的加起来应该会等于短的那一串。
这里有两个细节我踩过坑,一个是
"Ogn WtWj HneS"
"Ogn WtWj HneS"
一模一样,我两边都是3。变成6了,我就加了一个判断,左边如果完事儿了就直接返回。
另一个是
"A A AAa"
"A AAa"
左边1,右边2,加起来是3了。我就把right < shortLength改成了right < shortLength - left避免了重复。