先把每个句子分成一个个单词
然后比较即可,设置flag1、flag2,如果第一次出现不一样flag = 1,之后若一样flag2 = 1,若再次不一样,
同时若flag2 = 1,就是false
如果到最后短的句子没遍历到尾,则false
有A A
a A A a A A情形
如果从前向后比false, 则再从后向前比一次即可
class Solution { public: int split(string sentence, string words[110]) { int len = sentence.length(); int k = 0; for(int i = 0; i < len; i++) { if(sentence[i] == ' ') { k++; continue; } words[k] += sentence[i]; } return k + 1; } bool areSentencesSimilar(string sentence1, string sentence2) { string a[110], b[110]; if(sentence1.length() < sentence2.length()) { string tmp = sentence1; sentence1 = sentence2; sentence2 = tmp; } int len1 = split(sentence1, a); int len2 = split(sentence2, b); int i = 0, j = 0, flag1 = 0, flag2 = 0, flag3 = 0; for(int k = 0; k < len1; k++) { if(j < len2 && a[i] == b[j]) { i++, j++; if(flag1) flag2 = 1; } else { i++; flag1 = 1; if(flag2) flag3 = 1; } } if(flag3 || j < len2) { i = len1 - 1, j = len2 - 1, flag1 = 0, flag2 = 0, flag3 = 0; for(int k = len1 - 1; k >= 0; k--) { if(j >= 0 && a[i] == b[j]) { i--, j--; if(flag1) flag2 = 1; } else { i--; flag1 = 1; if(flag2) return false; } } if(j >= 0) return false; return true; } else { if(j < len2) return false; return true; } } };