微软2016校招笔试题

描述

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
程序:
package com.tanqil.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class FibonacciNumber {

 /**
  * @param args
  * @throws IOException
  */
 public static void main(String[] args) throws IOException {
  // 声明一个输入流,以886作为结束标志。
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  String buffer = null;
  String str = "";
  while ((buffer = br.readLine()) != null) {
   if (buffer.equals("886")) {
    break;
   }
   str += buffer;
  }
  br.close();
  // 声明一个treeset集合,用来存放数量满足fibonacci的子串。
  Set<String> set = new TreeSet<String>();
  // 遍历所有的子串,放入fibonacciNumber中验证是否满足条件,满足条件的放入set集合中。
  for (int i = 0; i < str.length(); i++) {
   for (int j = i + 1; j < str.length() + 1; j++)
    set = fibonacciNumber(str.substring(i, j), set);
  }
  // 遍历输出set结合中所有的子串。
  for (String s : set) {
   System.out.println(s);
  }

 }

 public static Set<String> fibonacciNumber(String str, Set<String> set) {
  // 声明一个list集合,用来存放100以内的斐波那契数。此处也可扩展利用递归得到所有的斐波那契数列。
  List<Integer> list = new ArrayList<Integer>();
  list.add(1);
  list.add(2);
  list.add(3);
  list.add(5);
  list.add(8);
  list.add(13);
  list.add(21);
  list.add(34);
  list.add(55);
  list.add(89);
  // 定义一个函数计算子串中不同字符的个数
  int count = fLength(str);
  // 如果子串的不同字符数量满足斐波那契数,将子串添加到set集合中。
  if (list.contains(count)) {
   set.add(str);
  }
  return set;
 }

 private static int fLength(String str) {
  // TODO Auto-generated method stub
  char[] ch = str.toCharArray();
  Set<Character> set = new HashSet<Character>();
  for (int i = 0; i < ch.length; i++) {
   set.add(ch[i]);
  }
  return set.size();
 }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值