zoukankan      html  css  js  c++  java
  • 删除字符串中重复的字符

    1.任意字符串,删除重复字符

     1 #include<iostream>
     2 using namespace std;
     3 void removeDuplicates(char *str)
     4 {
     5     bool tag[256]={false};
     6     int i,j;
     7     i=j=0;
     8     while(str[i]!='')
     9     {
    10         if(!tag[str[i]])
    11         {
    12             tag[str[i]]=true;
    13             str[j++]=str[i];
    14         }
    15         i++;
    16     }
    17     str[j]='';
    18 }
    19 void main()
    20 {
    21     char *str=new char;
    22     cin>>str;
    23     removeDuplicates(str);
    24     cout<<str;
    25 }

    2.字符串中只包含小写字母‘a'-'z'

     1 void removeDuplicates(char *str)
     2 {
     3     int check=0;     //int类型有4个字节,32位
     4     int i,j;
     5     i=j=0;
     6     while(str[i]!='')
     7     {
     8         int val=str[i]-'a';
     9         if((check&1<<val)==0)   //判断该字符是否存在过,若存在过,check的第val位和1<<val的第val位都为1,&运算后结果的第val位为1,即!=0
    10         {
    11             str[j++]=str[i];
    12             check|=1<<val;   //当该字符不存在时,1左移val位,每个字符对应32位中的1位,所以当该字符存在时,第val位为1    
    13         }
    14         i++;
    15     }
    16     str[j]='';
    17 }

    注:该方法仅适用于字符串全部为小写字母或全部为大写字母的情况,int为32位,可以表示26个字母

  • 相关阅读:
    ICMP协议
    观察者模式-Observer
    模板方法模式-Template Method
    Java的演变过程
    汉诺塔-Hanoi
    外观模式-Facade
    JDK5-增强for循环
    JDK5-可变参数
    动态代理与AOP
    代理模式-Proxy
  • 原文地址:https://www.cnblogs.com/mrlsx/p/5433068.html
Copyright © 2011-2022 走看看