← 都来码 / Dolaima← 例程索引r/school/rep_string.r 原文

r/school/rep_string.r · 999 字节 · 下载原文

# rep_string.r
# 来源 / Source: https://rosettacode.org/wiki/Rep-string
# 许可 / License: Rosetta Code 内容按 GNU FDL 1.3 发布(页面未另标许可)
# 说明 / Note: 整段照抄 / copied verbatim(字符串重复前缀判定,含 for 循环)
# ─────────────────────────────────────────────────────────────
is_repeated <- function(s) {
  for (i in 1 + (nchar(s) %/% 2):0) {
    if (startsWith(s, substring(s, i))) {
      return(i - 1)
    }
  }
}

test_strings <- c(
  "1001110011",
  "1110111011",
  "0010010010",
  "1010101010",
  "1111111111",
  "0100101101",
  "0100100",
  "101",
  "11",
  "00",
  "1"
)

result <- sapply(test_strings, is_repeated)
repeaters <- substring(test_strings, 1, result)
paste(
  test_strings, 
  "has a repetition length of",
  result,
  "with repeating unit",
  ifelse(repeaters != "", repeaters, "[none]")
) |> writeLines()