给你一个字符串 s 和一个字符串数组 dictionary 作为字典,找出并返回字典中最长的字符串,该字符串可以通过删除 s 中的某些字符得到。
    如果答案不止一个,返回长度最长且字典序最小的字符串。如果答案不存在,则返回空字符串。

    示例 1:

    输入:s = “abpcplea”, dictionary = [“ale”,”apple”,”monkey”,”plea”]
    输出:”apple”

    示例 2:

    输入:s = “abpcplea”, dictionary = [“a”,”b”,”c”]
    输出:”a”

    1. class Solution {
    2. /**
    3. 思路:
    4. (1)拿字典表中的字符串,分别和s做对比,当遇到匹配的元素的时候,就把s和从dictionary中正在
    5. 对比的字符串遍历位置都右移一个位置
    6. (2)如果没有匹配,就右移动s的字符串位置
    7. (3)当字典或者s跑到右边界,停止,这个时候如果匹配到,那么说明字典字符串的遍历位置刚好是字典字符串的长度
    8. */
    9. public String findLongestWord(String s, List<String> dictionary) {
    10. String storeString = "";
    11. // 对字典表进行遍历
    12. for(String target : dictionary){
    13. // 对比当前找到的字符串是不是最长
    14. // 即长度是不是最长,如果长度相等,那么ascii码是不是是否更大?
    15. // 如果是,不需要再次比较,直接返回即可
    16. int l1 = storeString.length(), l2 = target.length();
    17. if(l1 > l2 || (l1 == l2 && storeString.compareTo(target)<0)){
    18. continue;
    19. }
    20. // 判断是否是子串
    21. if(isSubStr(s, target)){
    22. storeString = target;
    23. }
    24. }
    25. return storeString;
    26. }
    27. // 判断是否是s的子串
    28. public boolean isSubStr(String s,String target){
    29. int i = 0;// s的遍历位置
    30. int j = 0;// j的遍历位置
    31. while(i < s.length() && j < target.length() ){
    32. // 当出现相等的时候,对j进行++
    33. if(s.charAt(i++) == target.charAt(j)){
    34. j++;
    35. }
    36. }
    37. return j == target.length();
    38. }
    39. }