计算机保研复试刷题——字串计算

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35564813/article/details/82501531

给出一个01字符串(长度不超过100),求其每一个子串出现的次数。
输入描述:
输入包含多行,每行一个字符串。
输出描述:
对每个字符串,输出它所有出现次数在1次以上的子串和这个子串出现的次数,输出按字典序排序。
示例1
输入
10101
输出
0 2
01 2
1 3
10 2
101 2

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner scanner=new Scanner(System.in);
        while(scanner.hasNext()){
            String str=scanner.next();
            **Map<String,Integer>map=new TreeMap<>();**
            int index=1;
            for(index=1;index<str.length();index++){
                for (int i = 0; i + index <= str.length(); i++) {
                    String sub = str.substring(i, i + index);
                    if(map.containsKey(sub)){
                        map.replace(sub,map.get(sub)+1);
                    }else{
                        map.put(sub,1);
                    }
                }
            }
            **for (Map.Entry<String, Integer> entry : map.entrySet()) {
                if (entry.getValue() > 1) {
                    System.out.print(entry.getKey() + " " + entry.getValue());
                    System.out.println();
                }
            }**
        }
    }
}

这里主要有个问题是字典序排序,使用treemap并将map进行遍历即可得到。即上述加粗部分

猜你喜欢

转载自blog.csdn.net/qq_35564813/article/details/82501531