NEED HELP! Why I can not just write result.add(tmp);


  • 0
    B

    public class Solution {
    public ArrayList<ArrayList<String>> partition(String s) {
    if(s == null) return null;
    ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>();
    ArrayList<String> tmp = new ArrayList<String>();
    calPartition(result, tmp, s);
    return result;
    }

    public void calPartition(ArrayList<ArrayList<String>> result, ArrayList<String> tmp, String s) {
        if(s.length() == 0) {
           //Here!!!!!When I write result.add(tmp); It won't accept. 
           //Said I return a wrong answer!
            ArrayList<String> suit = new ArrayList<String>(tmp);
            result.add(suit);
        }
        int len = s.length();
        for(int i = 1; i <= len; i ++) {
            String sub = s.substring(0, i);
            if(checkPali(sub)) {
                tmp.add(sub);
                String rest = s.substring(i);
                calPartition(result, tmp, rest);
                tmp.remove(tmp.size() - 1);
            }
        }
    }
    
    public boolean checkPali(String s) {
        if(s.length() % 2 == 1) return midPali(s);
        else return mirroPali(s);
    }
    
    public boolean midPali(String s) {
        int mid = s.length() / 2;
        int i = 0;
        while(2 * i + 1 <= s.length()) {
            if(s.charAt(mid - i) != s.charAt(mid + i)) return false;
            i ++;
        }
        return true;
    }
    
    public boolean mirroPali(String s) {
        int mid = s.length() / 2;
        int i = 0;
        while(2 * i + 2 <= s.length()) {
            if(s.charAt(mid - 1 - i) != s.charAt(mid + i)) return false;
            i ++;
        }
        return true;
    }
    

    }


Log in to reply
 

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