查找给定的循环旋转是否string1可以产生string2?
例子:-
字符串 1 = abcd
字符串 2 = cdab
true字符串 1 = abc
字符串 2 = bac
false我试图通过减少从复杂性,以提高这种逻辑n^2来n,并n要n-k通过使该checkRotation功能在找到第一个之后终止true。
//complexity n^2
def checkRotation(string1: String, string2: String): Boolean = {
for (i <- 0 until string1.length) yield {
for (j <- 0 until string2.length) yield {
if (string1.charAt(i) == string2.charAt(j)) {
string1 == string2.substring(j) + "" + string2.substring(0, j)
} else {
false
}
}
}
}.flatten.contains(true)
Run Code Online (Sandbox Code Playgroud)
//complexity n
def checkRotation(string1: String, string2: String, index: Int = 0): Boolean = {
if (index < string2.length) {
if (string1.charAt(0) != string2.charAt(index)) {
checkRotation(string1, string2, index + 1)
} else {
string1 == string2.substring(index) + "" + string2.substring(0, index)
}
} else {
false
}
}
Run Code Online (Sandbox Code Playgroud)
有什么改进吗?谢谢!!!
编辑
def checkRotation(string1: String, string2: String, index: Int = 0): Boolean = {
if (index < string2.length && (string1.charAt(0) != string2.charAt(index)
|| !string1.contains(string2.substring(index) + "" + string2.substring(0, index)))) {
checkRotation(string1, string2, index + 1)
} else {
index < string2.length
}
}
Run Code Online (Sandbox Code Playgroud)