JavaScript solution


  • 0
    D
    
    /**
     * @param {string[]} strs
     * @return {number}
     */
    var findLUSlength = function(strs) {
        
    // sort in ascending order of the length
       strs = strs.sort(sorter);
       let lengthArr = [];
       
      
        for(let m = 0; m < strs.length; m++){
          
          let currentStr = strs[m];
          let i = currentStr.length;
          let j = 0;
          let length =0;
          
          for(let n = 0; n < strs.length; n++){
            
            // we don't want to compare same string to itself
            if(m == n){
              continue;
            }
            
            
            let innerStr = strs[n];
            i = currentStr.length;
            
            // check if substring of current string is subsequence of other string
            while(i > 0){
              let subStr = currentStr.substr(0, i);
              
              // check if substring of current string is subsequence of other strings
              if(!isSubseq(subStr, innerStr)){
               
                length = subStr.length;
                break;
              }else {
                // substring of current string is found to be subsequence of some other string
                // so we are not interested
                length = 0;
              }
              i--;
              
            }
            
            // if current string is subsequence of at least one other string
            // we are not interested in such string.. so break the loop
            if(length == 0){
              break;
            }
          }
         
          
          lengthArr.push(length);
          
        }
        
      
       function sorter(a, b){
          if(a.length >= b.length) return 1;
          if(a.length < b.length) return -1;
        }
      
      
      // method to check if substring is subseq of other string
      function isSubseq(a, b){
        
        if(a.length > b.length){
          return false
        }
      
        let i = 0;
        let j = 0;
    
        while(i < a.length && j < b.length){
          if(a[i] != b[j]){
            j++
          }else {
            j++;
            i++;
          }
        }
    
        if(i == a.length){
          return true;
        }
    
        return false;
    
      }
      
      
      // return max subsequence length
      return Math.max(...lengthArr) > 0 ? Math.max(...lengthArr) : -1;
        
    };
    
    
    
    
    

Log in to reply
 

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