I will stick to writing Algorithm questions every week, whether simple or difficult!
Description:
Implements an algorithm to determine whether the characters in a string are unique (that is, there are no duplicates). No additional data structure can be used. (That is, only use the basic data structure)
Code:
# Include <iostream> # include <algorithm> # include <string> # include <assert. h> bool isunique (const STD: string & vstr) {If (vstr. size () = 0) return true; bool hash [128]; STD: Fill (hash, hash + 128, false); For (unsigned int I = 0; I <vstr. size (); ++ I) {int temp = vstr [I]; If (hash [temp]) return false; hash [temp] = true;} return true ;} bool isunique2 (const STD: string & vstr) {If (vstr. size () = 0) return true; int bucket [4] = {0, 0, 0, 0}; For (unsigned int I = 0; I <vstr. size (); ++ I) {int temp = vstr [I]; int num = temp/32; int mod = TEMP % 32; if (bucket [num] & (1 <mod) return false; bucket [num] |=( 1 <mod) ;}return true ;} int main () {STD: string test = "128 &"; STD: cout <isunique2 (TEST) <STD: Endl; _ assert (isunique (test) & isunique2 (TEST); System ("pause"); Return 0 ;}
Reference: http://hawstein.com/posts/1.1.html