remove the duplicate character in a string

/***
remove the duplicate in an unsorted array and return its new length of array.
adapt to any unsorted array with the template table of range table.
***/

int findIdx(string s, unordered_map<int, bool> wmap, int index) {
       while(index < s.size()) {
              if(!wmap[s[index]]) return index;
              index++;
       }
       return index;
}

int removedup(string str) {

       if(str.size() < 2) return str.size();

       unordered_map<int, bool> wordmap;
       for(int i=0; i<256; i++) {
              wordmap[i] = false;
       }

       int i=0, index=0;
       while(i<str.size() && index<str.size()) {
              if(!wordmap[str[i]]) {
                     wordmap[str[i++]] = true;
                     index++;
              } else {
                     index = findIdx(str, wordmap, index);
                     if(index == str.size()) break;

                     swap(str[index], str[i]);
                     wordmap[str[i++]] = true;
              }
              if(index == str.size()-1) break;
       }
       return i;
}

void main() {

       string S = "aabaaaaaaa";
       int len = removedup(S);s
       cout<<"test"<<endl;
}


Comments

Popular posts from this blog

Unique Binary Search Trees

Coin in Line