3

如何检查给定字符串是否是 R 中另一个给定字符串的循环旋转?例如:1234是循环旋转3412两次移位。但是我想检查一个字符串是否循环等效于另一个字符串,无论是多少班次。

4

3 回答 3

3

适应 Henrik 的评论,测试 (i) 是否nchar相等和 (ii) 如果一个向量在复制第二个向量后是另一个向量的一部分,似乎就足够了:

ff = function(x, y) (nchar(y) == nchar(x)) && (grepl(y, strrep(x, 2), fixed = TRUE))

ff("3412", "1234")
#[1] TRUE
于 2016-12-18T10:44:02.617 回答
2

您可以生成连续旋转,直到找到匹配项。如果没有一个旋转匹配,则字符串不是彼此的循环旋转。解决方案使用sub

cycrotT = function(s1,s2) {
  if (nchar(s1)!=nchar(s2)) {
    return(FALSE) }
  for (i in 1:nchar(s2)) {
    if (s1==s2) {
      return(TRUE) }
    # Move the first character to the end of the string
    s2 = sub('(.)(.*)', '\\2\\1', s2)
  }
  return(FALSE)
}


> cycrotT("1234567", "1324567")
# [1] FALSE
> cycrotT("1234567", "4567123")
# [1] TRUE
> cycrotT("1234567", "1234568")
# [1] FALSE
于 2016-12-15T03:06:11.450 回答
1

一个更长但可能更清晰的方法来做到这一点:

cyclic_index <- function(string1, string2) {

  ## gather info about the first string
  chars <- el(strsplit(string1, ""))
  length <- length(chars)
  vec <- seq_len(length)

  ## create a matrix of possible permutations
  permutations <- data.frame(matrix(NA, nrow = length, ncol = length + 1))
  names(permutations) <- c("id", paste0("index", vec))

  permutations$id <- vec

  ## calculate the offset indices
  for (r in vec)
    permutations[r, vec + 1] <- (vec + r - 1) %% (length)

  ## a %% a = 0 so reset this to a
  permutations[permutations == 0] <- length

  ## change from indices to characters
  permutations[ , vec + 1] <- sapply(vec, function(x) chars[unlist(permutations[x, vec + 1])])

  ## paste the characters back into strings
  permutations$string <- sapply(vec, function(x) paste0(permutations[x , vec + 1], collapse = ''))

  ## if string2 is a permutation of string1, return TRUE
  return(string2 %in% permutations$string)

}

cyclic_index("jonocarroll", "carrolljono")
#> TRUE

cyclic_index("jonocarroll", "callorrjono")
#> FALSE

cyclic_index("1234567", "4567123")
#> TRUE
于 2016-12-15T03:10:44.710 回答