勿忘《暴力解》:总是想着O(n),经常忽略暴力解。substr函数是个好函数

题目描述

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.勿忘《暴力解》:总是想着O(n),经常忽略暴力解。
2.substr函数 find 函数 是个好函数  充分利用C++ <string>里面的函数 不要自己造轮子。
substr 截取子字符串 find 字符串匹配 直接拿来用
3. 当涉及到字符串(或其他类型)排序( 多字符串排序。不要造轮子 )且去重时,可直接利用STL set<string>
4. auto 不能用于 set<>???

c++ string substr 方法 (截取子字符串)

返回一个从指定位置开始,并具有指定长度的子字符串。

str.substr(startpos, length);

其中 startpos 是起始字符的序号,必选,是所需的子字符串的起始位置。字符串中第一个字符的索引为 0。 length 是[从 startpos 开始]取的字符串长度(包括startpos )。 如果 length 为 0 或负数,将返回一个空字符串。如果没有指定该参数,则子字符串将延续到字符串的结尾。 如果要取得 str 中序号 m 到 n 之间(不包括n)的子字符串需要用

str.substr(m, n-m);

c++ string find  方法 (字符串匹配) 手写KMP算法?

查找函数 size_type find(const string& str, size_type pos = 0) const  当前string从pos开始向后查找str第一次出现的位置。

size_type find(const char* s, size_type pos, size_type n) const  当前string从pos开始向后查找“s子串内前n个字符组成字符串”第一次出现的位置。 

pos是描述当前string的,而n是描述s的。

代码如下:

#include <iostream>
#include <set>
#include <string>

using namespace std;

const int fibo[]={1,2,3,5,8,13,21};

int count_str(string s){
    int hash[26]={0};
    int num=0;
    for (int i = 0; i < s.size(); ++i)
    {
        if(hash[s[i]-'a']==0){
            ++num;
            hash[s[i]-'a']=1;
        }
    }
    return num;
}




int main()
{
    int hash[22]={0};
    for (int i = 0; i <=6 ; ++i)
    {
        hash[fibo[i]]=1;
    }
    string str;
    cin>>str;
    set<string> setstr;
    for (int len = 1; len <=str.size() ; ++len)
    {
        for (int i = 0; i <=str.size()-len; ++i)
        {
            string substr=str.substr(i,len);
            if(hash[count_str(substr)]==1){
                setstr.insert(substr);
            }
        }
    }
    /*
    for (auto str:setstr)
    {
        cout<<str<<endl;
    }*/
    set<string>::iterator it;
    for (it = setstr.begin(); it != setstr.end(); it++)
        cout << *it << endl;

    
    return 0;
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值