题目
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))
}