About Me

My photo
Mostly software programming related blogs.

Thursday, October 25, 2012

Check if unique characters in a string


C/C++ solution:

#include <string.h>
#include <iostream>

using namespace std;

main(int argc, char* argv[]) {

        string input ;
        cout << "Input string: ";
        cin >> input;

        bool val[26]; // assuming only english alphabets
        fill_n(val, 26, false);//{ [0 ... 25] = false };

        int len = input.size();

        if (len > 26) {
                cout << "string does not have unique characters." << "\n";
                return 0;
        }  
        while (len >= 0) {
                if(val[tolower(input[len-1]) - 'a'] == true) {
                        cout << "string does not have unique characters." << "\n";
                        break;
                } else {
                        val[tolower(input[len-1]) - 'a'] = true;
                }  
                len--;
           
        }  
        if (len < 0) {
                        cout << "string has all unique characters." << "\n";
        }  
}

No comments: