Time Limit Exceeded aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...


  • 0
    C

    Can any one tell me what is wrong with my code and where can I improve it?

    public ArrayList<String> wordBreak( String s, Set<String> dict )
       {
          HashMap<Integer, ArrayList<String>> result = new HashMap<Integer, ArrayList<String>>();
          ArrayList<String> firstLetter = new ArrayList<String>();
    
          if( dict.contains( s.substring( 0, 1 ) ) )
             firstLetter.add( s.substring( 0, 1 ) );
          if( !firstLetter.isEmpty() )
             result.put( 0, firstLetter );
          
          for( int i = 1; i < s.length(); i++ )
          {
             ArrayList<String> currentLetter = new ArrayList<String>();
    
             if( dict.contains( s.substring( 0, i + 1 ) ) )
                currentLetter.add( s.substring( 0, i + 1 ) );
    
             for( int j = 0; j < i; j++ )
             {
                if( result.containsKey( j ) )
                {
                   if( dict.contains( s.substring( j + 1, i + 1 ) ) )
                   {
                      for( String each : result.get( j ) )
                      {
                         currentLetter.add( each + " " + s.substring( j + 1, i + 1 ) );
                      }
                   }
                }
             }
             if( !currentLetter.isEmpty() )
             {
                result.put( i, currentLetter );
             }
          }
          return result.containsKey( s.length() - 1 ) ? result.get( s.length() - 1 ) : new ArrayList<String>();
       }

Log in to reply
 

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