您的位置:首页 > 产品设计 > UI/UE

Array Question 1 unique string

2015-11-23 01:26 302 查看
Array question 1:

Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures.

Because we are not allowed to use additional data structures. so we could not use array to store the checking result. 

The first thing I can think of is scanning the characters of the string one by one and compare it with all the characters after it. But it will cost us O(n^2) time. So we can use a structure like array to check it. Use the value of the character as the index
of the array and if there is another same character, then the corresponding array will already has value. So we can know the characters of the string is not unique.

1). Pay attention to attach " #include<string>"

2). There are so many functions that you can use in the C++ string library. Like size() , at(), length(), etc;

#include<iostream>

#include<string>

using namespace std;

 int main()

{

    string s;

        cout<<"please input your string:"<<endl;
cin>>s;
int i;
int* b;

        for(i=0;i<s.size();i++)

      {

        char a;

        a=s.at(i);

        

       if(b[a])

       {

           cout<<"The string is ununique!"<<endl;

            return 0;

       }

       else
{
 b[a]=1;
}

      }

       cout<<"The string is unique!"; 

}

time: O(n)  Space: O(1)

Using bit vector:

There is another more convenient way to save the memory. We can use an integer to store the checking result. Transform each character into one bit in the integer "1" using"<<'(shift) and "|" . Check using "&".

#include<iostream>

#include<string>

using namespace std;

 int main()

{

    string s;

        cout<<"please input your string:"<<endl;
cin>>s;
int i;
int check=0;

        for(i=0;i<s.size();i++)

      {

        int a;

        a=s.at(i)-'a';  //the character will be tansformed to 1 to 26

        

       if((1 << a) & check) //shift 1 to the position of index a

       {

           cout<<"The string is ununique!"<<endl;

            return 0;

       }

       else
{
 check=(1<<a)|check;
}

      }

       cout<<"The string is unique!"; 

}

time O(n), space O(1)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: