Confirm the Ending算法
题目
检查一个字符串(str)是否以指定的字符串(target)结尾。
如果是,返回true;如果不是,返回false。
Tips
String.substr()
- confirmEnding(“Bastian”, “n”) 应该返回 true.
- confirmEnding(“Connor”, “n”) 应该返回 false.
- confirmEnding(“Walking on water and developing software from a specification are easy if both are frozen”, “specification”) 应该返回 false.
- confirmEnding(“He has to give me a new name”, “name”) 应该返回 true.
- confirmEnding(“He has to give me a new name”, “me”) 应该返回 true.
- confirmEnding(“He has to give me a new name”, “na”) 应该返回 false.
- confirmEnding(“If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing”, “mountain”) 应该返回 false.
思路
取最后几位的值(str.length - target.length)来和target的值来匹配,那么用substr方法来取最后几位的值,然后if else判断就可以了。
代码
1 | function confirmEnding(str, target) { |
然后想着如何优化一下,其实直接可以全等嘛…….
1 | function confirmEnding(str, target) { |
我想了想,感觉应该没有比这个更优的解法了,不然还能怎么验证呢,于是上StackOverflow去搜索了一下。
1 | function end(str, target) { |
刚开始看半天没怎么理解这句话什么意思,但是又去仔细看了看substr的用法,一下子明白了。
题目中的从tips里面说白了就是和target的一样,那么直接从str.substr(-target.length)取值不就是target的值么…….
不得不说有时候不能着眼于你怎么去和别的值配对,拿别的值来作为target来匹配,效率提升。
Confirm the Ending算法