lifeiteng

524. Longest Word in Dictionary through Deleting

Sep 26th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.92 KB | None | 0 0
  1. class Solution {
  2.     public String findLongestWord(String s, List<String> d) {
  3.         int len = 0, clen = 0;
  4.         String res = "";
  5.         for(String w : d)
  6.         {
  7.             if(lcs(s, w))
  8.             {
  9.                 len = w.length();
  10.                 if(len >= clen)
  11.                 {
  12.                     if(len > clen) res = w;
  13.                     if(len == clen && res.compareTo(w) >= 0)
  14.                         res = w;
  15.                     clen = len;                    
  16.                 }
  17.             }
  18.         }
  19.         return res;
  20.     }
  21.    
  22.     boolean lcs(String a, String b)
  23.     {
  24.         int m = a.length(), n = b.length(), i = 0, j = 0;
  25.         if(m < n) return false;
  26.         while(i < m && j < n)
  27.         {
  28.             if(a.charAt(i) == b.charAt(j))
  29.             {
  30.                 i++;
  31.                 j++;
  32.             }
  33.             else i++;
  34.         }
  35.         return j == n;
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment