LintCode 1377: Find Substing

原题如下:
1377. Find Substring
Given the length k, find all substrings of length k in the string str.The characters of a substring can not be repeated and output the number of substrings that satisfy such conditions (the same substring is counted only 1 times).

Example
Given str = “abc”, k = 2, output 2.

Explanation:
Characters are not repeated, and substrings of length k have “ab”, “bc”.
Given str = “abacb”, k = 1, output 3.

Explanation:
Characters are not repeated, and substrings of length k have “a”, “b”.”c”.
Notice
|str| <= 100000.
k <= 100000.
All characters are lowercase.

解法1:
我的解法是利用set的去重性。这题可以用2个set,一个去掉重复的string,一个去掉重复的char。我用的一个dup[26]来去重char,速度会稍快一点。
代码同步在
https://github.com/luqian2017/Algorithm

class Solution {
public:
    /**
     * @param str: The string
     * @param k: The length of the substring
     * @return: The answer
     */
    int findSubstring(string &str, int k) {
        int len = str.size();
        set<string> ss;
        int upperBound = len - k;
        
        for(int i = 0; i <= upperBound; ++i) {
            string sub_str = str.substr(i, k);
            if (check(sub_str)) {
                ss.insert(sub_str);
            }
        }
        return ss.size();
    }

private:
    bool check(string &str) {
        vector<bool> dup(26, false);
        int len = str.size();
        for (int i = 0; i < len; ++i) {
            int index = str[i] - 'a';
            if (dup[index]) return false;
            dup[index] = true;
        }
        return true;
    }
    
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值