Help! Output from leetcode and local(Eclipse) is not the same?


  • 0
    W

    LeetCode said:
       Input: 2
       Output: ["()()","(())","()()()","(()())","()(())","((()))","(())()"]
       Expected: ["(())","()()"]
    In my Eclipse, I got the expected answer. I can't understand why leetcode gives that output which apprently is correct when n is 2 plus n is 3. From my code, I can see it comming not possible. Code below.

    public class Solution {
    public static List<StringBuilder> arrangeResult = new ArrayList<>();
    public List<String> generateParenthesis(int n) {
    List<String> result = new ArrayList<>();
    if(n==0) return result;
    if(n==1){
    result.add("()");
    return result;
    }
    //Generate 2n parenthesis, n "(" and n ")"
    String[] str = new String[2
    n];
    for(int i=0;i<n;i++){
    str[i] = "(";
    }
    for(int j = n; j<2n; j++){
    str[j] = ")";
    }
    //generate all the possibilities
    List<StringBuilder> list = arrange(str,1,2
    n);
    // remove the repetition
    HashSet<String> finalResult = new HashSet<>();
    for(StringBuilder sb : list){
    String temp = sb.toString();
    //choose the ones that are legal
    if(isLegal(temp)){
    finalResult.add(temp);
    }
    }
    for (String string : finalResult) {
    result.add(string);
    }
    return result;
    }
    // Swap chars in a String[] based on their index
    public static void swap(String[] str,int i,int j){
    String temp = new String();
    temp = str[i];
    str[i] = str[j];
    str[j] = temp;
    }
    //Generate all the possibilities with a string[] containing n "(" and n ")"
    public static List<StringBuilder> arrange (String[] str, int st, int len){
    if(st==len-1){
    StringBuilder sb = new StringBuilder();
    for(int i = 0 ;i <len; i++){
    sb.append(str[i]);
    }
    arrangeResult.add(sb);
    }else{
    for(int i = st; i <len; i++){
    swap(str,st,i);
    arrange(str,st+1,len);
    swap(str,st,i);
    }
    }
    return arrangeResult;
    }
    // use a stack to check if the parentheses are grammatical correct
    public static boolean isLegal(String str){
    Stack s = new Stack();
    Boolean flag = true;
    try{
    to:for(int i = 0; i < str.length(); i++){
    char c = str.charAt(i);
    switch(c){
    case '(':
    s.push(c);
    break;
    case ')':
    char p = (char) s.pop();
    if(p!='('){
    flag = false;
    break to;
    }
    }
    }
    }catch(Exception e){
    flag = false;
    }
    if(!s.isEmpty()){
    flag = false;
    }
    return flag;
    }
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.