-
-
Save kayfay/3f3b5f2dbaaef35ac02616d8288b415e to your computer and use it in GitHub Desktop.
reverse_string.R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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