알고리즘 공부 2020. 8. 24. 23:13

https://leetcode.com/problems/word-break-ii/

 

Word Break II - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

/**
 * @param {string} s
 * @param {string[]} wordDict
 * @return {boolean}
 */
var wordBreak = function(s, wordDict) {
    var res=[];
    var map=[];
    for( var i=0; i<s.length+1; ++i )     map[i] = 0;
    
    var find = function( p_str, p_arr )
    {
        if( s.indexOf(p_str) != 0)      
            return false;  
        
        if( p_str.length > s.length )   
            return false;        
        else
        {
            if( p_str == s )
            {
                res.push(p_arr.join(' '));            
                return true;
            }
            else
            {            
                var refstr = '';
                for( var i=0; i<wordDict.length; ++i )
                {
                    refstr = p_str+wordDict[i];                   
                    
                    if( s.indexOf(refstr) >= 0 )
                    {
                        if( map[refstr] == 1 )  return false;
                        result = find( refstr, p_arr.concat([wordDict[i]]) );                        
                        if( result === false )               map[refstr] = 1;
                    }
                }
                
                return !(res.length==0);
            }
        }           
    }    
    find('',[]);
    return res;
};
posted by Sense.J
: