TreeSet

TreeSet的特点

TreeSet的元素是顺序存储的,并且不会有重复的的元素。

TreeSet举例

设有A,B两个字符串,给定一个数k,找出A中所有长度为k的不重复的子串在B中出现的次数的和。

import java.util.*;
public class example{
	public static void main(String[] args) {
		Scanner scan=new Scanner(System.in);
		while(scan.hasNext()) {
			int k=scan.nextInt();//输入有一个整数k
			String A=scan.next();//输入字符串A
			String B=scan.next();//输入字符串B
			TreeSet<String> set=new TreeSet<String>();//定义一个TreeSet,用来获取A中不重复的子串
			int len=A.length();
			for(int i=0;i<len+1-k;i++) {
				set.add(A.substring(i, i+k));
			}
			List<String> temp=new ArrayList<>();
			for(String string:set) {
				temp.add(string);//由于TreeSet没有get的方法,因此另外定义一个List存储TreeSet里面的元素,放便后面进行索引。
			}
			int len1=set.size();
			int count=0;
			for(int i=0;i<len1;i++) {
				int startindex=0;
				while(true) {
					int index=B.indexOf(temp.get(i),startindex);//从startindex以后的位置查找出A中子串在B中的第一次出现的位置
					if(-1!=index) {
						startindex=index+1;
						count++;
					}
					else {
						break;
					}
				}
			}
			System.out.println(count);
		}
	}
}

Reference:

  1. indexOf https://www.cnblogs.com/zhangshi/p/6502987.html
  2. TreeSet的性质 https://www.cnblogs.com/yzssoft/p/7127894.html
  3. TreeSet的输出 https://zhidao.baidu.com/question/1864283240489115227.html
  4. substring https://www.cnblogs.com/jack-Leo/p/6683356.html
  5. java list的基本操作 https://blog.csdn.net/qq_33505051/article/details/78967362
  6. 获取某个字符串出现的个数 https://blog.csdn.net/qq_41563799/article/details/79978614
不当之处,敬请批评指正。
原文地址:https://www.cnblogs.com/wumh7/p/9656955.html