My Java solution using HashMap. Any suggestion?


  • 0
    X
    public class Solution {
    Map<String, Boolean> map = new HashMap<String, Boolean>();
    public boolean wordBreak(String s, Set<String> wordDict) {
    	if (map.containsKey(s))
    		return map.get(s);
    
    	if (s.isEmpty())
    		return true;
    	int l = s.length();
    	for (int i = 0; i < l; i++) {
    		if (wordDict.contains(s.substring(0, i + 1))) {
    			String newString = s.substring(i + 1);
    			boolean breakNewString = wordBreak(s.substring(i + 1), wordDict);
    			map.put(newString, breakNewString);
    			if (breakNewString)
    				return true;
    		}
    	}
    	return false;
    }
    }

Log in to reply
 

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