[经典面试题][搜狗]在一个字符串中寻找包含全部出现字符的最小字串

题目

一个字符串中含有n个字符,其中有m个不同的字符,n>>m,用最少的时间和空间找到包含所有这m个字符的最短的字串,不考虑特殊字符,只考虑字母数字即可。
例如:
abccbaddac, 返回:cbad
aabcadbbbcca,返回:bcad

思路

[算法系列之二十二]包含T全部元素的最小子窗口
本题目相比连接中所说的稍微简单一些,本题目不用考虑重复字符。

代码

    /*---------------------------------------------
    *   日期:2015-02-24
    *   作者:SJF0115
    *   题目: 包含全部出现字符的最小字串
    *   来源:搜狗
    *   博客:
    -----------------------------------------------*/
    #include <iostream>
    #include <climits>
    using namespace std;

    string MinWindow(string S){
        int slen = S.size();
        if(slen <= 0){
            return "";
        }//if
        int minWinStart,minWinEnd;
        int minWinLen = INT_MAX;
        // 统计不同字符个数
        int m = 0;
        int needFind[256] = {0};
        for(int i = 0;i < slen;++i){
            needFind[S[i]] = 1;
        }//for
        for(int i = 0;i < 256;++i){
            if(needFind[i] == 1){
                ++m;
            }//if
        }//for

        int hasFound[256] = {0};
        int val;
        int count = 0;
        for(int start = 0,end = 0;end < slen;++end){
            val = S[end];
            ++hasFound[val];
            if(hasFound[val] <= 1){
                ++count;
            }//if
            // 找到一子串包含全部不同的字符
            if(count == m){
                int startEle = S[start];
                while(hasFound[startEle] > 1){
                    --hasFound[startEle];
                    ++start;
                    startEle = S[start];
                }//while

                int curWinLen = end - start + 1;
                if(minWinLen > curWinLen){
                    minWinLen = curWinLen;
                    minWinStart = start;
                    minWinEnd = end;
                }//if
            }//if
        }//for
        if(count != m){
            return "";
        }//if
        return S.substr(minWinStart,minWinEnd - minWinStart + 1);
    }

    int main() {
        string S("aabcadbbbcca");
        cout<<MinWindow(S)<<endl;
    }

引用:

[算法系列之二十二]包含T全部元素的最小子窗口

相似题目:

[LeetCode]76.Minimum Window Substring

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@SmartSi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值