Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

ruby - How to write recursive and optimal solution for decoding the compressed string?

I found a problem statement over the internet, was trying to solve it in ruby.

Input and output are self explanatory.

Eg. 1, Input : 2[abc]3[ab]c

Output : abcabcabcababababc

Explanation : 2 times abc and 3 times ab and then c

Eg. 2 Input : 2[3[a]b]

Output : aaabaaab

I tried this, But it doesn't work for multiple level.

num = 1
str = ""
"3[abc]4[ab]2[3[a]b]c".each_char do |ch|
  if ch.to_i != 0
    num = ch
  elsif ch == "["
    next
  elsif ch == "]"
    num.to_i.times { print str }
    str = ""
    num = 1
  else
    str << ch
  end
end

I was looking for recursive call.

question from:https://stackoverflow.com/questions/65600955/how-to-write-recursive-and-optimal-solution-for-decoding-the-compressed-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
str = "2[abc]3[ab]c2[de]fg"
str.gsub(/(d+)[(p{L}+)]/) { $2*$1.to_i }  
  #=> "abcabcabababcdedefg"
  #    ^^^^^^
  #          ^^^^^^
  #                 ^^^^

We can write the regular expression in free-spacing mode to make it self-documenting.

/
(d+)     # match one or more digits, save to capture group 1 
[        # match '[' 
(p{L}+)  # match one or more letters, save to capture group 2
]        # match ']'
/x        # invoke free-spacing regex definition mode

For the first match,

$1 #=> "2"
$2 #=> "abc"

so the block becomes

"abc"*2
  #=> "abcabc"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...