面試題:求最長非重複子序列面試題35:第一個只出現一次的字元

來源:互聯網
上載者:User

題目:求字串的最長非重複子序列。比如字串“dabaccdeff”,它的最長非重複子序列為“dabcef”

這道題目與 面試題35:第一個只出現一次的字元 非常相似。都可以通過對字串球雜湊來解。

View Code

#include<iostream>#include <stack>  #include<stdlib.h>using namespace std;void print(char *s,int len,char *hashtable);int NoReplicatedSubstring(char *s,int len){        const int tablesize=256;    char *hashtable=new char[tablesize];    int i;    int j;    int count=0;    //初始化hash[]    for(i=0;i<tablesize;i++)    {        hashtable[i]='\0';    }    //第一次掃描    for(i=0;i<len;i++)    {        hashtable[s[i]]=s[i];//將字元存入雜湊表中        //cout<<hashtable[s[i]];    }    /*    //方法0,按字元順序輸出字串中的非重複子序列。    for(i=0;i<tablesize;i++)    {        if(hashtable[i]!='\0')        {            cout<<hashtable[i];        }    }        /* //方法1,按字串順序輸出非重複子序列    for(i=0;i<len;i++)    {        if(hashtable[s[i]]!='\0')        {            count++;            cout<<hashtable[s[i]];            hashtable[s[i]]='\0';        }    }    */    //輸出方法2,按字串逆序輸出非重複子序列    stack<char> c;//建立一個棧    for(i=len-1;i>=0;i--)    {        if(hashtable[s[i]]!='\0')        {            c.push(hashtable[s[i]]);            count++;            hashtable[s[i]]='\0';        }    }    //輸出棧中的內容    while(!c.empty())    {        cout<<c.top();        c.pop();    }    cout<<endl;    return count;}void main(){    char *s="dabaccdeff";    int len=strlen(s);    int count=NoReplicatedSubstring(s,len);    system("pause");}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.