字符串去重

题目:求字符串的最长非重复子序列。比如字符串“dabaccdeff”,它的最长非重复子序列为“dabcef”

#include<iostream>
#include <stack>  
#include<stdlib.h>
using namespace std;

int NoReplicatedSubstring(char *s,int len)
{    
    const int tablesize=256;
	char hashtable [tablesize] = {'0'};
    int count=0;
    for(int i=0;i<len;i++)
      hashtable[s[i]]=s[i];
    
    stack<char> c;//创建一个栈
    for(int i=0;i < len;i++)
    {
        if(hashtable[s[i]]!='\0')
        {
            c.push(hashtable[s[i]]);
            hashtable[s[i]]='\0';
			count++;
        }
    }
    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");
}

更简单的方法就是用set

#include <iostream>
#include <set>
using namespace std;

void NoReplicatedSubstring(char *s,int len) 
{
	set <char> HashMap;
	for(int i=0;i<len;i++)
		HashMap.insert(s[i]);

	set <char>::iterator itr = HashMap.begin();
	for(itr;itr!=HashMap.end();itr++)
		cout<<*itr<<",";
};

int main()
{
	char *s="dabaccdeff";  
	int len=strlen(s);  
	NoReplicatedSubstring(s,len);  
	system("pause");
	return 0;
}



 

阅读更多
换一批

没有更多推荐了,返回首页