记录自己在CodeWars解决的问题(一)字符串比较

这篇博客记录了作者在CodeWars上遇到的一个挑战,即判断第一个字符串是否以第二个字符串结尾。作者提供了自己的解决方案,主要利用ArrayList的contains方法进行检查,并通过一系列测试用例验证了方法的正确性。博主邀请读者分享更优的解题方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:
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

有好的更好的方法请回复。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值