C + + Learning

Source: Internet
Author: User

Determine if there are duplicate characters in the string

1. Question: Is the ASCII string or Unicode string, if the ASCII string can only have 256 characters, when the length of the string exceeds 256, there must be repeated characters

2. Determine if there are any characters appearing two times

#include <iostream>
#include <string>
#include <memory.h>
using namespace Std;
BOOL IsUnique (String str)
{
if (Str.length () >256)
return false;
BOOL isexist[256];
memset (Isexist,false, sizeof (isexist));
int count=0;
for (int i=0;i<str.length (); i++)
{
int val=str[i];
if (Isexist[val])
{
return false;
}
Else
{
Isexist[val]=true;
cout<<val<<endl;
cout<<str[i]<<endl;

}

}
return true;
}
int main ()
{
String str= "abc";
BOOL Isnodup;
Isnodup=isunique (str);
if (isnodup)
cout<< "No DUP" <<endl;
Else
cout<< "DUP" <<endl;
return 0;

}

Or, with the displacement method, which one appears each time is set to 1 (with the number of displacements expressed). With the number of displacements before and if there is repetition with the result greater than 0.

However, consider how many bits the data type corresponds to, assuming that the int type (32-bit) can only be used to contain characters less than 32 bits, assuming only lowercase ' a '-' Z '.

BOOL IsUnique2 (String str) {    if (str.length () >26)        return false;    int checker=0;    for (int i=0;i<str.length (); i++)    {        int val=str[i]-' a ';        cout<<val<<endl;            if ((checker& (1<<val)) >0)                return false;            Checker |= (1<<val);  cout<<checker<<endl;    }    return true;}

There are other solutions, such as whether check each character is duplicated, but with a high degree of time complexity.

C + + Learning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.