码迷,mamicode.com
首页 > 其他好文 > 详细

524. Longest Word in Dictionary through Deleting

时间:2017-07-05 15:22:01      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:nbsp   com   long   global   har   cti   遍历   int   str   

https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/#/solutions

 

An alternate, more efficient solution which avoids sorting the dictionary:

public String findLongestWord(String s, List<String> d) {
    String longest = "";   // 用来比较的local
    for (String dictWord : d) {  // 题意: 顺序遍历
        int i = 0;               // 每次都得从target头部开始遍历
        for (char c : s.toCharArray())   // 判断字符串的每一个字母相等用toCharArray
            if (i < dictWord.length() && c == dictWord.charAt(i)) i++; 题意: 比较

        if (i == dictWord.length() && dictWord.length() >= longest.length()) //判断是否满足题意
            if (dictWord.length() > longest.length() || dictWord.compareTo(longest) < 0) // 是否满足两点, 更新global, 
                                          学会s.compareTo(ss) 来比较字典顺序
         longest = dictWord;
  }
  return longest;
}

Time Complexity: O(nk), where n is the length of string s and k is the number of words in the dictionary.

  

524. Longest Word in Dictionary through Deleting

标签:nbsp   com   long   global   har   cti   遍历   int   str   

原文地址:http://www.cnblogs.com/apanda009/p/7121213.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!