【发布时间】:2016-09-07 05:44:51
【问题描述】:
给定一个字符串,我想计算每个可能出现在字符串中的子字符串。例如,给定一个字符串
str = "abab"
我想计算所有可能的子字符串及其值:
"A" = 2
"B" = 2
"AA" = 0
"AB" = 2
"BA" = 1
"BB" = 0
我写了一个函数如下:
countSubstrings <- function(string_try ="", items = NULL )
{
string_try <- toupper(string_try)
if(is.null(items))
{
items <- strsplit(string_try, "")[[1]]
}
n <- length(unique(items))
counts_substrings <- c()
substrings_all <- c()
for (i in 1:n) # Number of characters in substring
{
substrings_combo <- gtools::permutations(n, i, unique(items), repeats=TRUE)
print(paste("The number of combinations is: ",
nrow(substrings_combo), "for substrings of length", i))
for(j in 1:nrow(substrings_combo))
{
tosearch <- paste(substrings_combo[j,], collapse = "")
substrings_all <- c(substrings_all, tosearch)
total <- sum(grepl(tosearch,
sapply(1:(nchar(string_try) - 1),
function(ii) substr(string_try, ii, ii + 1))))
counts_substrings <- c(counts_substrings, find_overlaps(tosearch, string_try))
}
}
return(list(substrings_all,counts_substrings))
}
它可以满足我的要求,但速度非常慢。我看到一个潜在的缺陷,即使“aa”的出现为零,我的程序也会考虑子字符串“aaa”。这在序列分析和模式挖掘中很流行。我想知道是否已经有更快的实现或者可以以某种方式进行优化。需要一个 R 解决方案。
【问题讨论】: