A string s is LUCKY if and only if the number of different characters in s is a fibonacci number. Gi

题目描述

A string s is LUCKY if and only if the number of different characters in s is a fibonacci number. Given a string consisting of only lower case letters , output all its lucky non-empty substrings in lexicographical order. Same substrings should be printed once. 
输入描述:
a string consisting no more than 100 lower case letters.


输出描述:
output the lucky substrings in lexicographical order.one per line. Same substrings should be printed once.

输入例子:
aabcd

输出例子:
a 
aa 
aab 
aabc 
ab 
abc 
b 
bc 
bcd 
c 
cd 
d

一晚上就做了这一道题,必须纪念下!

才知道TreeSet是有序的,HashSet是无序的,要是把HashSet排序很麻烦。。。

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;

public class Main {

	public static void main(String[] args) {
		Main main = new Main();
		// main.findLucky("aabcd"); // 在牛客网上提交时,不能人为赋值,否则提交失败,
		Scanner scanner = new Scanner(System.in);
		String input = scanner.next();
		// Date date = new Date();
		// long t1 = date.getTime();
		// System.out.println(t1);
		main.findLucky(input);
		// long t2 = date.getTime();
		// System.out.println(t2);
		// System.out.println(t2-t1);// ///有序输出
	}// /main

	void findLucky(String string) {

		// int[] fib = { 0, 1, 2, 3, 5, 8, 13, 21 };// /使用ArrayList fib有两个1,所以a
		// a 会出现两次!!!

		long[] fib = new long[100];
		fib[0] = 0L;
		fib[1] = 1L;
		for (int i = 2; i <= 50; i++) {
			fib[i] = fib[i - 1] + fib[i - 2];
			// / System.out.println(fib[i]);// ///有序输出
			// fib[i-2]=fib[i-1]; ///用了for循环不用再替换!!!
			// fib[i-1]=fib[i];
		}
		// fib[2] = -1;
		// ArrayList<String> list = new ArrayList<String>();
		// list.add("");
		Set<String> hsResult = new TreeSet<String>();
		// HashSet<Character> hs = new HashSet<Character>();
		Set<Character> hs = new HashSet<Character>();
		int length = string.length();
		for (int i = 0; i < length; i++) {
			for (int j = i + 1; j <= length; j++) {
				String subString = string.substring(i, j);
				for (int k = 0; k < subString.length(); k++) {
					hs.add(subString.charAt(k));
				}
				for (int m = 0; m < fib.length; m++) {
					if (fib[m] == hs.size()) {

						hsResult.add(subString);
					}
				}
			}
			hs.clear();
		}
		Iterator<String> it = hsResult.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());// ///有序输出
		}

	}// /findLucky

}


你可能感兴趣的:(算法,微软,Lucky)