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
分析
字串處理,主要是找到子串,然後判斷子串裡不同的字元數。主要由三個難點:
1、判斷子串裡不同字元個數,可以用一個大小為26char陣列來解決:如果出現過就置1,如果沒有出現過就是預設的0.(用count函式解決)
2、主要就是要生成全部的substring,以及26以內的fibonacci數列。
26以內的fibonacci數列只有 1 2 3 5 8 13 21 34 55 89,用一個const int陣列可以表示。然後用STL裡的find函式來判斷是否為fibonacci數列。
3、構建子串,用STL裡的string的substr(int i,size_t size)可以解決。
補充:斐波那契數列(Fibonacci sequence),又稱黃金分割數列、因數學家列昂納多·斐波那契(Leonardoda Fibonacci)以兔子繁殖為例子而引入,故又稱為“兔子數列”,指的是這樣一個數列:1、1、2、3、5、8、13、21、34、……在數學上,斐波納契數列以如下被以遞迴的方法定義:F(0)=0,F(1)=1, F(n)=F(n-1)+F(n-2)(n>=2,n∈N*)在現代物理、準晶體結構、化學等領域,斐波納契數列都有直接的應用。
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
int count(string s) {
int p[26] = { 0 }, R = 0;
for (int i = 0; i<s.length(); i++)
if (p[s[i] - 'a'] == 0) {
R++;
p[s[i] - 'a'] = 1;
}
return R;
}
int main() {
string str;
set<string> s;
cin >> str;
const int fibonacci[] = { 1,2,3,5,8,13,21};
vector<int> vec1(fibonacci, fibonacci + 7);
int n = 1;
while (n<str.length()) {
for (int i = 0; i <= str.length() - n; i++) {
string ss = str.substr(i, n);
if (find(vec1.begin(), vec1.end(), count(ss)) != vec1.end())
s.insert(ss);
}
n++;
}
set<string>::iterator it;
for (it = s.begin(); it != s.end(); it++)
cout << *it << endl;
return 0;
}