mport java.util.ArrayList; import java.util.Collections; import java.util.Map.Entry; import java.util.Scanner; import java.util.TreeMap; import java.util.TreeSet; public class Test04 { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("请输入大字符串:"); String da=sc.nextLine(); System.out.println("请输入小字符串:"); String xiao=sc.nextLine(); TreeMap<String ,Integer> tm=new TreeMap<>(); for (int i = 0; i < xiao.length(); i++) { if(da.contains(xiao.charAt(i)+"")){ //如果包含对应索引字符 String str=xiao.substring(i); for (int j = 0; j < str.length(); j++) { String zi=str.substring(0, j+1); if(da.contains(zi)){ tm.put(zi ,zi.length()); } } } } //System.out.println(tm); ArrayList<Integer> al=new ArrayList<>(); for (Entry<String ,Integer> en: tm.entrySet()) { al.add(en.getValue()); } Collections.sort(al); int b=al.get(al.size()-1); for (Entry<String ,Integer> en: tm.entrySet()) { if(en.getValue() == b){ System.out.println("最大子字符串是:"+en.getKey()); } } } } |