This problem can be easily solved by using a buffer array of the type bool which will act as a check parameter to see if the character already occurred in string or not .
lets start coding :-
#include<iostream.h>
#include<conio.h>
#include<cstring.h>
bool checkUnique(string s)
{
bool a[256];
memset(a,0,sizeof(a)) ;
int len = s.length();
for(int i=0;i<len;i++)
{
int pos = (int)s[i] ;
if(a[pos]) return false ;
a[pos] = 1 ;
}
return true ;
}
int main (){
string s1 = "Hello this is my first post" ;
string s2 = "qwertyuiopasdfgghjklzxcvbnm" ;
cout<<checkUnique(s1)<<endl ;
cout<<checkUnique(s2)<<endl ;
return 0 ;
}
Here what i used is a for loop in which i pick a character convert it into integer (its ascii value) and check at that location what array "a" holds .
if its "1" that means the character is repeated and its not unique otherwise continue the loop .
lets start coding :-
#include<iostream.h>
#include<conio.h>
#include<cstring.h>
bool checkUnique(string s)
{
bool a[256];
memset(a,0,sizeof(a)) ;
int len = s.length();
for(int i=0;i<len;i++)
{
int pos = (int)s[i] ;
if(a[pos]) return false ;
a[pos] = 1 ;
}
return true ;
}
int main (){
string s1 = "Hello this is my first post" ;
string s2 = "qwertyuiopasdfgghjklzxcvbnm" ;
cout<<checkUnique(s1)<<endl ;
cout<<checkUnique(s2)<<endl ;
return 0 ;
}
Here what i used is a for loop in which i pick a character convert it into integer (its ascii value) and check at that location what array "a" holds .
if its "1" that means the character is repeated and its not unique otherwise continue the loop .
No comments:
Post a Comment