蓝桥杯java 算法训练 统计单词个数

问题描述
  给出一个长度不超过200的由小写英文字母组成的字母串(约定;该字串以每行20个字母的方式输入,且保证每行一定为20个)。要求将此字母串分成k份 (1<k<=40),且每份中包含的单词个数加起来总数最大(每份中包含的单词可以部分重叠。当选用一个单词之后,其第一个字母不能再用。例 如字符串this中可包含this和is,选用this之后就不能包含th)。
  单词在给出的一个不超过6个单词的字典中。
  要求输出最大的个数。
输入格式
  第一行有二个正整数(p,k)
  p表示字串的行数;
  k表示分为k个部分。
  接下来的p行,每行均有20个字符。
  再接下来有一个正整数s,表示字典中单词个数。(1<=s<=6)
  接下来的s行,每行均有一个单词。
输出格式
  每行一个整数,分别对应每组测试数据的相应结果。
样例输入
1 3
thisisabookyouareaoh
4
is
a
ok
sab
样例输出
7
数据规模和约定
  长度不超过200,1<k<=40,字典中的单词数不超过6。

 

import java.util.Scanner;

public class Main{
	static int p;
	static int k;
	static String S;
	static int wordSize;
	static String word[];
	static int num = 0;
	static int cut;//分割
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		p = sc.nextInt();
		k = sc.nextInt();
		S = sc.nextLine();
		S = "";
		for(int i=0;i<p;i++){
			S = S + sc.nextLine();
		}
		wordSize = sc.nextInt();
		word = new String[wordSize];
		for(int j=0;j<wordSize;j++){
			word[j] = sc.next();		
		}
		wordCount(S);
		if(cut<k) {
			num = num-(k-1);
		}
		System.out.println(num);
	}
	
	public static void wordCount(String S){
		for(int i=0;i<S.length();i++) {
			for(int j=0;j<wordSize;j++) {
				if(S.substring(i,S.length()).length()<word[j].length()) {
					continue;
				}
				if(S.substring(i,i+word[j].length()).length()<word[j].length()){
					continue;
				}
				if(S.substring(i,i+word[j].length()).equals(word[j])) {
					//System.out.println(S+":"+word[j]);
					num++;
					//System.out.println("第"+num);
					if(i!=0) {
						cut++;
						//System.out.println("分割:"+cut);
					}
					wordCount(S.substring(i+1,S.length()));
					return;
				}
			}
		}
	}	
}

  

posted @ 2018-01-24 16:35  谨言&慎独_yk  阅读(471)  评论(0编辑  收藏  举报