题目:
Description:Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
solution(‘abc’, ‘bc’) // returns true
solution(‘abc’, ‘d’) // returns false
自己解决方法:主用List中的contains来检查值是否存在;
public static boolean solution(String str,String ending) {
Listlist=new ArrayList();
char[] charStr=str.toCharArray();
char[] charEnding=ending.toCharArray();
if(charStr.length<charEnding.length) {
return false;
}
for(int i=0;i<charStr.length;i++) {
list.add(charStr[i]+"");
}
boolean isOk=true;
for(int j=0;j<charEnding.length;j++) {
System.out.println(“e:”+charEnding[j]);
isOk= list.contains(charEnding[j]+"");
}
return isOk;
}
测试:
System.out.println(solution(“abc”,“a”));
输出:true
System.out.println(solution(“abc”,“b”));
输出:true
System.out.println(solution(“abc”,“c”));
输出:true
System.out.println(solution(“abc”,“ab”));
输出:true
System.out.println(solution(“abc”,“ac”));
输出:true
System.out.println(solution(“abc”,“bc”));
输出:true
System.out.println(solution(“abc”,“abc”));
输出:true
System.out.println(solution(“abc”,“d”));
输出:false
有好的更好的方法请回复。
这篇博客记录了作者在CodeWars上遇到的一个挑战,即判断第一个字符串是否以第二个字符串结尾。作者提供了自己的解决方案,主要利用ArrayList的contains方法进行检查,并通过一系列测试用例验证了方法的正确性。博主邀请读者分享更优的解题方法。
580

被折叠的 条评论
为什么被折叠?



