2019.01.24(一)难度:7

题目

Input:

a string strng
an array of strings arr

Output of function containAllRots(strng, arr):
a boolean true if all rotations of strng are included in arr (C returns 1)
false otherwise (C returns 0)

我自己的实现方法:

fun containAllRots(strng:String, arr:ArrayList<String>):Boolean {
        val charList = strng.toMutableList()
        val stringList = ArrayList<String>()
        for (count in 0 until charList.size){
            val temp = charList.first()
            for (index in 0 until charList.size){
                if (index < charList.size - 1){
                    charList[index] = charList[index + 1]
                }else{
                    charList[index] = temp
                }
            }
            stringList.add(StringBuilder().apply {
                for (char in charList){
                    this.append(char)
                } 
            }.toString())
        }

        var result = true
        for (item in stringList){
            result = result and arr.contains(item)
        }
        
        return result
    }

最高票数答案:

fun containAllRots(strng:String, arr:ArrayList<String>):Boolean {
    return arr.containsAll(List(strng.length) { (strng.drop(it) + strng.take(it)) })
}

解析:
一个长度为n的字符串首位循环一周共有n种组合,因此获取所有组合的字符串再分别判断是否存在于目标List中即可。

应当掌握kotlin的方法:

生成一个长度为size的列表,具体元素的值由表达式返回值决定

/**
 * Creates a new read-only list with the specified [size], where each element is calculated by calling the specified
 * [init] function. The [init] function returns a list element given its index.
 * @sample samples.collections.Collections.Lists.readOnlyListFromInitializer
 */
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
public inline fun <T> List(size: Int, init: (index: Int) -> T): List<T> = MutableList(size, init)

获取字符串删掉前n位字符后的子字符串

/**
 * Returns a string with the first [n] characters removed.
 * 
 * @sample samples.collections.Collections.Transformations.drop
 */
public fun String.drop(n: Int): String {
    require(n >= 0) { "Requested character count $n is less than zero." }
    return substring(n.coerceAtMost(length))
}

获取字符串前n位的子字符串

/**
 * Returns a string containing the first [n] characters from this string, or the entire string if this string is shorter.
 * 
 * @sample samples.collections.Collections.Transformations.take
 */
public fun String.take(n: Int): String {
    require(n >= 0) { "Requested character count $n is less than zero." }
    return substring(0, n.coerceAtMost(length))
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值