改进逻辑以在给定的 string1 上找到循环旋转可以产生 string2

Pun*_*y V 0 logic scala

查找给定的循环旋转是否string1可以产生string2

例子:-

字符串 1 = abcd

字符串 2 = cdab

输出 = true

字符串 1 = abc

字符串 2 = bac

输出 = false

我试图通过减少从复杂性,以提高这种逻辑n^2n,并nn-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)

Tim*_*Tim 5

尝试这个:

(string1 + string1).contains(string2)
Run Code Online (Sandbox Code Playgroud)