My Java recursive solution. Easy


  • 0
    Q
     public class Solution {
        Map<String, Boolean> mem = new HashMap<String, Boolean>();
        public boolean isInterleave(String s1, String s2, String s3) {
            if (s1.length() + s2.length() != s3.length()){
                return false;
            } 
            else if (s3.length() == 0){
                return true;
            }
            else if (mem.containsKey(s1+"#"+s2)){
                return mem.get(s1+"#"+s2);
            }
    
            boolean b = (s1.length()>0 && s1.charAt(0)==s3.charAt(0))?isInterleave(s1.substring(1), s2, s3.substring(1)):false;
            if (!b){
                b = (s2.length()>0 && s2.charAt(0)==s3.charAt(0))?isInterleave(s1, s2.substring(1), s3.substring(1)):false;
            }
            mem.put(s1+"#"+s2, b);
            return b;
        }
    }

Log in to reply
 

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