码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Generate Parentheses

时间:2014-09-06 01:00:42      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   ar   for   div   sp   

public class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<String>();
        Stack<Integer> numStack = new Stack<Integer>();
        int nowNum = n;
        boolean nowNumPoped = false;

        while (!(nowNumPoped && nowNum == n)) {
            if (!nowNumPoped) {
                if (nowNum>0) {
                    numStack.push(nowNum);
                    if (numStack.size()+nowNum == n+1)
                        nowNum--;
                } else {
                    result.add(generateString(numStack,n));
                    nowNum = numStack.pop();
                    nowNumPoped = true;
                }
            } else {
                nowNum--;
                nowNumPoped = false;
            }

        }
        return result;
    }
    
    public String generateString(Stack<Integer> numStack, int n) {
        int rightParentheses = 0;
        StringBuffer resultString = new StringBuffer();

        for (int i=0; i<n; i++) {
            resultString.append("(");
            int tmpIndex = n-i-1;
            if (tmpIndex<numStack.size()) {
                while (rightParentheses<numStack.get(tmpIndex)) {
                    resultString.append(")");
                    rightParentheses++;
                }
            }
        }

        return resultString.toString();
    }

}

 

[LeetCode] Generate Parentheses

标签:style   blog   color   os   io   ar   for   div   sp   

原文地址:http://www.cnblogs.com/yuhaos/p/3958930.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!