:: [intv] First non repeated character. ::
HOME


[Date Prev][Date Next][Date Index]

[intv] First non repeated character.


//Problem: Find the first non repeated character in a string.
//Save as: main.cpp and compile as: g++ -o main main.cpp

#include <iostream>
#include <string>
#include <map>

using namespace std;

typedef map<char, int, less<char> > MAP;

int firstNonRepeatChar(string&);

int main(){
  string s1 = "aabccdeef";

  cout << "First Non repeated Character in " << s1 << "is " << s1[firstNonRepeatChar(s1)] << endl;

}

int firstNonRepeatChar(string& s2){

  MAP hash;
  MAP::iterator itr;

  for (int i = 0; i < s2.length(); i++){
    itr = hash.find(s2[i]);
    if (itr == hash.end()){
      //Hash value not found
      hash.insert(MAP::value_type(s2[i], 1));
    }else{
      //hash value found
      itr->second++;
    }

  }

  for (int i = 0; i < s2.length(); i++){
    itr = hash.find(s2[i]);
    if (itr->second == 1){
      return i;
    }
  }

  //Printing the hash table (optional)
  for (itr = hash.begin(); itr != hash.end(); ++itr){
    cout << itr->first << '\t' << itr->second << endl;
  }

  return 0; //returns zero on error.

}


Comments and corrections are appreciated and can be sent to papers@mia.ece.uic.edu. Click here for ©opyright information.