Given an encoded string, return its decoded string.
Input: s ="3[a]2[bc]"Output:"aaabcbc"
defdecodeString(self,s:str) ->str: stack = [] line ='' num =0 i =0while i <len(s): c = s[i]if c.isdigit(): num =int(c)while i+1<len(s)and s[i+1].isdigit(): num =10*num +int(s[i+1]) i +=1elif c =='[': stack.append(line) stack.append(num) line ='' num =0elif c ==']': pre_num = stack.pop() pre_line = stack.pop() pre_line += line * pre_num line = pre_lineelse: line += c i +=1return line
Recursive: 放進recursion的string必須是完整[]的內容,並更新index
publicStringdecodeString(String s) {String str ="";int num =0;for(int i=0; i<s.length(); i++){char c =s.charAt(i);if(Character.isDigit(c)) num = num*10+ c -'0';elseif( c =='[') {int count =1;int iter = i+1;while(count !=0){if(s.charAt(iter) =='[') count++;if(s.charAt(iter) ==']') count--; iter++; } iter--;String concate =decodeString(s.substring(i+1, iter));for(int j=0; j<num; j++){ str += concate; } num =0; i = iter; }else str += c; }return str;}
443. Decode Compression
Given an array of characters, compress it in-place.
Input:["a","b","b","b","b","b","b","b","b","b","b","b","b"]Output:Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].Explanation:Since the character "a" does not repeat, it is not compressed."bbbbbbbbbbbb" is replaced by "b12".Notice each digit has it's own entry in the array.
defcompress(self,chars: List[str]) ->int: n =len(chars) read, write =0,0while read<n: c = chars[read] chars[write]= c write +=1 count =1while read+1< n and chars[read+1]== c: read+=1 count+=1 read+=1if count >1:for c2 instr(count): chars[write]= c2 write +=1return write
Valid Express (Bloomberg)
Given a string of balanced expression, find if it contains a redundant parenthesis or not. A set of parenthesis are redundant if same sub-expression is surrounded by unnecessary or multiple brackets.
defvalidExpress(s): count =0 innest =False stack = []for c in s:if c in'+-*/':continueelif c =='(': stack.append(count) innest =True count =0elif c ==')':if (innest and count <=1) or (not innest and count ==0):returnFalse count = stack.pop() innest =Falseelse: count +=1returnTrueprint(validExpress('((a+b))'))print(validExpress('(a+(b)/c)'))print(validExpress('(a*(c-d))'))print(validExpress('(a+b*(c-d))'))
Compress String (Quantcast)
Write a method that can take a "compressed" string and decompress it.