Skip to content

Instantly share code, notes, and snippets.

@kayfay
Created January 8, 2019 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kayfay/3f3b5f2dbaaef35ac02616d8288b415e to your computer and use it in GitHub Desktop.
Save kayfay/3f3b5f2dbaaef35ac02616d8288b415e to your computer and use it in GitHub Desktop.
reverse_string.R
s <- c("ab(dc)a")
reverseParentheses <- function(s) {
# split the string vector into character vectors
s <- strsplit(s, NULL)[[1]]
# recrusively call and operate on the character vector
for (i in seq_along(s)) {
if (s[i] == "(") {
begin <- i
}
if (s[i] == ")") {
final <- i
# create a new reverse 'string' segmenting,
# collapsing, and reversing inner pairs
# also removing parenthese by incrementing/decrementing
rev.string <- paste(c(s[1:(begin - 1)],
rev(c(s[(begin + 1):(final - 1)])),
s[(final + 1):length(s)]),
sep = "",
collapse = "")
# use recrusion to repeat on innermost parentheses
rev.string <- reverseParentheses(rev.string)
}
}
return(rev.string)
}
reverseParentheses(s)
# expecting "abcda"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment