Q: String Element Uniqueness

less than 1 minute read

Array Element Uniqueness

**Problem1: ** An algorithm to determine if a string has only unique chars.

**Addition: ** What if you cannot use any additional data structure.?

testset=[('ASsdCr',False),('aa',True),('',False)]

def checkUniqeness(mystring):
    if len(mystring)==0: return False
    chars=set()
    for c in mystring:
        if c in chars: 
            return True
        else: 
            chars.add(c)
    return False

def checkUniqeness2(mystring):
    a=sorted(mystring)
    lastc=''
    for c in a:
        if c==lastc: return True
        else: lastc=c
    return False

cforcount=0           
for i,testi in enumerate(testset):
    if checkUniqeness2(testi[0])==testi[1]: 
        cforcount+=1
        
print 'Test %d/%d is correct' % (cforcount,len(testset))

        
Test 3/3 is correct