[cc150] 1.3

 Design an algorithm and write code to remove the duplicate characters in a string without using any additional buffer. NOTE: One or two additional variables are fine. An extra copy of the array is not.

FOLLOW UP

Write the test cases for this method.

如果可以使用O(1)的空间的话,就用个naive的hash来做吧

  
  
  
  
  1. class Solution { 
  2. public
  3.     void removeDuplicates(char *str){ 
  4.         vector<bool> exist(256, 0); 
  5.         char *p = str; 
  6.         int cnt = 0; 
  7.         while (*p) { 
  8.             if(exist[*p]){ 
  9.                 cnt++; 
  10.             }else
  11.                 exist[*p] = 1; 
  12.                 *(p-cnt) = *p; 
  13.             } 
  14.              
  15.             p++; 
  16.         } 
  17.         p--; 
  18.         for (int i = 0; i < cnt; i++) { 
  19.             *(p-i) = 0; 
  20.         } 
  21.     } 
  22. }; 

如果不可以的话,那就排序O(nlogn)再做

如果连排序都不行的话,只能O(n^2)了

你可能感兴趣的:(cc150)