微軟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();
 }
}

發佈了27 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章