No DP, is this a O(n) complexity, O(1) space solution?


  • -1
    M
     public boolean wordBreak(String s, Set<String> dict) {
            
            int start = 0;
            for (int i = 1; i <= s.length(); i++) {
                String sub = s.substring(start, i);
                if(dict.contains(sub)) {
                   start = i; 
                }
            }
        
            int end = 0;
            for (int i = s.length(); i > end; i--) {
                String sub = s.substring(end, i);
                if (dict.contains(sub)) {
                    end = i;
                    i = s.length() + 1;
                }
            }
            
            return start == s.length() || end == s.length();
    
     }

  • 0
    G

    This is a test case. s = "goalspecial"; dic = {"go", "goal", "goals", "special"};


  • 0

    Thank you! I have just added your test case and the above code now gets Wrong Answer.


Log in to reply
 

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