001 unique string

Source: Internet
Author: User

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


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.