Lucky String – 微軟筆試
標籤(空格分隔): 算法
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
描述:
一個字符串是Lucky的當且僅當它裏面字符的數目爲Fibonacci數列中的一個數。如果給出一個字符串,它裏面只包含小寫字母,輸出它所有的除空字符串外的Lucky SubString,每個子串只能被輸出一次。並且輸出的子串按照字典序列排序。
思路:
對於整個字符:
1. 依次遍歷字符串,截取子串
2. 統計子串中的字符種類數,判斷是否已經在結果集中出現或者是否符合Fibonacci數列
3. 調用集合類的字符串排序算法,按照字典序列將結果集輸出。
代碼如下:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class LuckyString {
/**
* 給定一個字符串s,統計它裏面一共出現了多少種字符
* @param s
* @return
*/
public static int count(String s) {
char[] ch = s.toCharArray();
boolean[] letter = new boolean[26];
for(int i=0; i<26; i++)
letter[i] = false;
int res = 0;
for(int i=0; i<ch.length; i++) {
if(letter[ch[i]-'a'] == false) {
letter[ch[i] -'a'] = true;
res++;
}
}
return res;
}
/**
* 二分查找一個數是否在給定數組中出現
* @param nums
* @param n
* @return
*/
public static int binearySearch(int[] nums, int n) {
int left = 0, right = nums.length-1, mid = (left+right)/2;
while(left <= right) {
if(nums[mid] < n) {
left = mid + 1;
}
else if(nums[mid] > n)
right = mid - 1;
else return mid;
mid = (left + right) / 2;
}
return -1;
}
/**
* 解決問題的主要函數。
* 1. 依次遍歷字符串,截取子串
* 2. 統計子串中的字符種類數,判斷是否已經在結果集中出現或者是否符合Fibonacci數列
* 3. 調用集合類的字符串排序算法,按照字典序列將結果集輸出。
* @param s
*/
public static void solve(String s) {
int[] fibo = {1,2,3,5,8,13,21,34,55,89};
List<String> res = new ArrayList<String>();
for(int i=0; i<s.length(); i++) {
for(int j=i+1; j<s.length()+1; j++) {
String sub = s.substring(i, j);
int num = count(sub);
if(binearySearch(fibo, num) >= 0 && !res.contains(sub)) //包含該數
res.add(sub);
}
}
Collections.sort(res);
for(int i=0; i<res.size(); i++)
System.out.println(res.get(i));
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
String s = sc.nextLine();
solve(s);
}
}
}