A concise Java solution. (11-line in wordBreak function)


  • 27
    2
    public class Solution {
        
        public boolean wordBreak(String s, Set<String> wordDict) {
            int len = s.length();
            boolean[] f = new boolean[len+1];
            f[0] = true;
            for (int i=1; i<len+1; i++)
                for (int j=0; j<i; j++)
                    if (f[j] && wordDict.contains(s.substring(j,i)))
                    {
                        f[i] = true;
                        break;
                    }
            return f[len];
        }
    }

  • 0
    I

    @2guotou

    I feel like we don't need to break after setting

    f[i] = true;
    

  • 1
    C

    @ivanlw It will still work without break, but I think it saves a lot of time if you break when you found a word, so you don't have to loop through the rest.


Log in to reply
 

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