題目:求字串的最長非重複子序列。比如字串“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");}