题目来源:
leetcode题目,网址:2490. 回环句 - 力扣(LeetCode)
解题思路:
首先判断第一个字符和最后一个字符是否相等,若不想等,肯定不是回环句。然后根据空格分割字符串获得字符串数组。最后遍历得到的字符串数组,判断每个字符串的最后一个字符与下一个字符串的首个字符是否相等即可。
解题代码:
class Solution {
public boolean isCircularSentence(String sentence) {
if(sentence.charAt(0)!=sentence.charAt(sentence.length()-1)){
return false;
}
String[] words=sentence.split(" ");
for(int i=0;i<words.length-1;i++){
if(words[i].charAt(words[i].length()-1)!=words[i+1].charAt(0)){
return false;
}
}
return true;
}
}
总结:
官方题解也是首先判断第一个字符与最后一个字符是否相等,但他接下来以空格为基准判断其前后字符是否相等,效率更高。