codewars练习(javascript)-2021/2/23

本文介绍了在Codewars平台上进行的两项JavaScript练习:ReversedStrings,实现字符串反转功能;Wordsearch,通过复杂排序找到目标单词在列表中的位置。分享了三种解决方案,包括基本操作、时间复杂度过高及优化过的二分查找法。

codewars-js练习

2021/2/23

github 地址

my github地址,上面有做的习题记录,不断更新…

【1】<8kyu>【Reversed Strings】

Complete the solution so that it reverses the string passed into it.

example

'world'  =>  'dlrow'

solution

<script type="text/javascript">
        function solution(str){
            return str.split('').reverse().join('')
        }
    
        // 验证
        console.log(solution('hello'));// 'olleh'
        console.log(solution(''));// ''
	</script>
【2】<6kyu>【Word search】

You are given a word target and list of sorted(by length(increasing), number of upper case letters(decreasing), natural order) unique words words which always contains target, your task is to find the index(0 based) of target in words,which would always be in the list.

您将得到一个单词目标和一个排序(按长度(增加)、大写字母数量(减少)、自然顺序)的唯一单词单词,这些单词总是包含target,您的任务是查找target在单词中的索引(基于0),它总是在列表中。

(列表按长度(从小到大)排序,然后按大写字母数量(最大到最小),然后按自然顺序排序)

example

words = ['JaCk', 'Jack', 'jack', 'jackk', 'COdewars', 'codeWars', 'abcdefgh', 'codewars']
'''
(list is sorted by length(small to big), then by number of uppercase letters(maximum to minimum) and then by natural order)
'''
target = 'codewars'
//result should be 7

//Another example:
words = ['cP', 'rE', 'sZ', 'am', 'bt', 'ev', 'hq', 'rx', 'yi', 'akC', 'nrcVpx', 'iKMVqsj']
target = 'akC'
//result should be 9

solution

第一种 超出时间

//90ms 期望less than 58ms
function indexOf(words, target){
            // return words.indexOf(target) 
        }

第二种 超出时间

//100ms 期望less that 90ms
function indexOf(words, target){
            for(var i=0;i<words.length;i++){
                if(words[i]==target){
                    return i
                }
            }
        }

第三种 二分查找 pass

<script type="text/javascript">
        function indexOf (words, target) {
            // 二分法查找
            let first = 0, last = words.length - 1;
            while (first < last) {
                let middle = parseInt((first + last) / 2);  
                if (words[middle].length < target.length) {
                    first = middle + 1;
                } else {
                    last = middle - 1;
                }
            }
            return words.indexOf(target, first);
        };
    
        // 验证
        console.log(indexOf(['JaCk', 'Jack', 'jack', 'jackk', 'COdewars', 'codeWars', 'abcdefgh', 'codewars'], 'codewars'));// 7
        console.log(indexOf(['cP', 'rE', 'sZ', 'am', 'bt', 'ev', 'hq', 'rx', 'yi', 'akC', 'nrcVpx', 'iKMVqsj'], 'akC'));// 9
	</script>

以上为自己思路供大家参考,可能有更优的思路。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值