字符串解码 栈与递归

方法一:利用两个栈


public class ZiFuChuanJieMa {

	public static void main(String[] args) {
		Solution6 a = new Solution6();
		
		
		System.out.println(a.decodeString("3[ab]"));

	}

}
class Solution6 {
    public String decodeString(String s) {
    	char[] a = s.toCharArray();
    	Stack<Integer> i1 = new Stack<Integer>();
    	Stack<String> s1 = new Stack<String>();
    	int num = 0;
    	for(int i = 0;i < s.length();i++) {
    		if(Character.isDigit(a[i])) {
    			num  = num * 10 + Integer.parseInt(String.valueOf(a[i])); 
    		}else if(a[i] == '[') { 			
    			i1.push(num);
    			s1.push(String.valueOf(a[i]));
    			num = 0;	
    		}else if(Character.isLetter(a[i])) {
    			s1.push(String.valueOf(a[i]));
    		}else {
    			int b = i1.pop();
    			String x = new String();  			
    			while(!s1.peek().equals("[")) {
    				x = s1.pop() + x;			
    			}
    			s1.pop();
    			String c = new String();
    			
    			while(b > 0) {
    				c += x;
    				b--;
    			}
    			s1.push(c);
    			
    		}
    	}
    	String d = new String();
    	while(!s1.isEmpty()) {
    		d = s1.pop() + d;
    	}
    	return d;
    }
}

方法二 : 递归

package com.leetcode;

import java.util.Arrays;
import java.util.Stack;

public class ZiFuChuanJieMa {

	public static void main(String[] args) {
		Solution6 a = new Solution6();
		
		
		System.out.println(a.decodeString("3[ab]"));

	}

}

class Solution6 {
	public String decodeString(String s) {
		return dfs(s, 0)[0];
	}

	private String[] dfs(String s, int i) {
		StringBuilder res = new StringBuilder();
		int multi = 0;
		while (i < s.length()) {
			if (s.charAt(i) >= '0' && s.charAt(i) <= '9')
				multi = multi * 10 + Integer.parseInt(String.valueOf(s.charAt(i)));
			else if (s.charAt(i) == '[') {
				String[] tmp = dfs(s, i + 1);
				i = Integer.parseInt(tmp[0]);//一次走完括号 i直接变为 ] 的下标
				while (multi > 0) {
					res.append(tmp[1]);
					multi--;
				}
			} else if (s.charAt(i) == ']')
				return new String[] { String.valueOf(i), res.toString() };//[]内部的
			else//是字母的情况
				res.append(String.valueOf(s.charAt(i)));//加入字符串 a ab
			i++;
		}
		return new String[] { res.toString() };//while走完后的
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值