1. 程式人生 > >Leetcode -- 394. Decode String

Leetcode -- 394. Decode String

inside rul ted script form you 給定 rac 會有

Given an encoded string, return it‘s decoded string.

The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.

You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.

Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won‘t be input like 3a or 2[4].

Examples:

s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".

思路: 一個DFS的題目, 給定的字符串可能會有嵌套很多層, 在每一層我們只要在碰到正常的字符就保存到當前層的結果中, 如果碰到數字就另外保存起來作為倍數, 碰到‘[‘ 就進入下層遞歸, 碰到‘]‘ 就將當前層結果返回, 這樣在返回給上層之後就可以用倍數加入到上層結果字符串中. 最終當所有層都完成之後就可以得到結果. 在不同層次的遞歸中, 我們可以維護一個共同的位置索引, 這樣在下層遞歸完成之後上層可以知道已經運算到哪裏了.

DFS的思想: ?

Leetcode -- 394. Decode String