Check if unique chars

Check if a given string contains unique characters.  Eg: "Hello" contains duplicates, therefore should return false (0).  "Doing" contains unique chars and therefore should return true (1).
/*
 * UniqueChars.cpp
 *
 *  Created on: Apr 10, 2012
 *      Author: Kiran Hegde
 */

#include <string>
#include <iostream>

using namespace std;

/**
 * works with any ASCII char
 */
bool isUniqueChars(string &str) {
    if (str.length() > 256) return false;
    bool charSet[256];
    for (int i=0; i<256; i++) {
        charSet[i] = false;
    }
    for (unsigned int i=0;i<str.length(); i++) {
        int val = str[i];
        if (charSet[val]) {
            return false;
        }
        charSet[val] = true;
    }
    return true;
}

/**
 * Test the function
 */
int main() {
    string words[] = {"hello", "world", "what", "abcdefghijklmnopqrstuvwxyz123456789"};
    for (int i=0; i < 4; i++) {
        cout << "Word: " << words[i] << " Unique? " << isUniqueChars(words[i]) << endl;
    }
    cout << endl;
}
Comments