牛客网——子串计算

题目描述

给出一个01字符串(长度不超过100),求其每一个子串出现的次数。

输入描述:

输入包含多行,每行一个字符串。

输出描述:

对每个字符串,输出它所有出现次数在1次以上的子串和这个子串出现的次数,输出按字典序排序。

链接:https://www.nowcoder.com/questionTerminal/bcad754c91a54994be31a239996e7c11
来源:牛客网

import java.util.ArrayList;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String line;
        while (input.hasNextLine()) {
            line = input.nextLine();
            parse(line);
        }
    }
    private static void parse(String line) {
        String subLine;
        Map<String, Integer> map = new TreeMap<String, Integer>();
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < line.length(); i++) {
            for (int j = i + 1; j <= line.length(); j++) {
                subLine = line.substring(i, j);
                if (subLine.length() != line.length()) {
                    list.add(subLine);
                    map.put(subLine, 0);
                }
            }
        }
        for (int i = 0; i < list.size(); i++) {
            for (Map.Entry<String, Integer> entry : map.entrySet()) {
                if (list.get(i).equals(entry.getKey())) {
                    entry.setValue(entry.getValue() + 1);
                }
            }
        }
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            if (entry.getValue() > 1) {
                System.out.print(entry.getKey() + " " + entry.getValue());
                System.out.println();
            }
        }
    }
}

 

posted @ 2019-01-07 22:40  JAYPARK01  阅读(283)  评论(0编辑  收藏  举报