LeetCode#524通過刪除字母匹配到字典裡最長單詞-java中CompareTo方法用法以及Comparator中Compare方法返回值
阿新 • • 發佈:2020-07-13
import java.util.Collections; import java.util.Comparator; import java.util.List; /* 524. 通過刪除字母匹配到字典裡最長單詞 給定一個字串和一個字串字典,找到字典裡面最長的字串,該字串可以通過刪除給定字串的某些字元來得到。如果答案不止一個,返回長度最長且字典順序最小的字串。如果答案不存在,則返回空字串。 示例 1: 輸入: s = "abpcplea", d = ["ale","apple","monkey","plea"] 輸出: "apple" 示例 2: 輸入: s = "abpcplea", d = ["a","b","c"] 輸出: "a" 說明: 所有輸入的字串只包含小寫字母。 字典的大小不會超過 1000。 所有輸入的字串長度不會超過 1000 */ public class p524 { /*public String findLongestWord(String s, List<String> d) { Collections.sort(d, new Comparator<String>() { @Override public int compare(String o1, String o2) { if(o1.length()!=o2.length()){ return o2.length()-o1.length(); } else { int len=o1.length(); return o1.compareTo(o2); } } }); String res=""; for(String str:d){ if(isChildXulie(s,str))return str; } return res; }*/ public String findLongestWord(String s, List<String> d){ String res=""; for(String str:d){ if(isChildXulie(s,str)){ int len=str.length(); if(len>res.length()){ res=str; } else if(len==res.length()) { res=res.compareTo(str)>0?str:res; } } } return res; } public boolean isChildXulie(String s1,String s2){//判斷S2是不是s1的子序列 int j=0; for(int i=0;i<s1.length();i++){ if(j<s2.length()&&s1.charAt(i)==s2.charAt(j)){ j++; } } if (j==s2.length()){ return true; } return false; } }
執行結果:
註釋掉的:
第二種方法:
CompareTo方法:
Comparator中Compare方法返回值:
返回值為1則交換兩個值,返回值小於等於0不做交換