Microsoft Interview Question
void replacetoken(char* a, char * b)
{
int ptrR = 0;
int ptrW = 0;
while(a[ptrR]!='/0')
{
int flag =0;
flag = isToken(&a[ptrR],b);
switch(flag)
{
case -1:
return;
case 0:
a[ptrW] = a[ptrR];
ptrW++;
ptrR++;
break;
default:
a[ptrW] = ' ';
ptrW++;
ptrR = ptrR + flag;
break;
}
}
}
int isToken(char * a, char * b)
{
int i=0;
while(a[i]!='/0' & b[i]!='/0')
{
if(a[i]!=b[i])
return 0;
i++;
}
if(b[i]!='/0' && a[i]=='/0')
return -1;
return i;
}
First of all, although looks simple, this is actually a very good exercise.
IMHO, the output should be an array of string, string[]. So den's solution is not complete.
====================================================
void del(char* a, char* b, vector<string>& result){
....if ((a!=NULL)&& (b!=NULL)){
....//step 1: count the size of b;
....char* sb=b;
....int size=0;
....while(*sb){
........size++;
........sb++;
....}
....//compare each letter in a.
....char* start=a;
....char* end;
....char segment[30];
....while(*a){
........char* pa, *pb;
........pa=a;
........pb=b;
........for(; *pb!=0; pa++, pb++){
............if (*pb!=*pa)
................break;
........}
........if(*pb==0){
............end=pa-size;
............int i=0;
............//copy the segment
............while(i<end-start){
................*(segment+i)=*(start+i);
................i++;
............}
............*(segment+i+1)='\0';
............result.push_back(string(segment));
............start=pa+1;
........}
........a++;
....}
........//copy the last segment
........if(*a==0)
............result.push_back(string(start));
....}
}
int main()
{
....char* a="who is the man who saw the eagle today went the wrong way?";
....char* b= "the";
....vector<string> result;
....del(a, b, result);
....for(int i=0; i<result.size(); i++)
........cout<<result[i]<<endl;
}
Essentially, this is another variant for KMT algo.
http://www.careercup.com/question?id=61953
Essentially, this is another variant for KMT algo.
http://www.careercup.com/question?id=61953
char** func(char* S, char* D)
{
if(!S||!D) return null;
int idx=0;
char** substr=null;
int count=0;
int len=0;
while(S[idx])
{
if(s[idx]==D[0]&&S[idx+1]==D[1]&&S[idx+2]==D[2])
{
if(len>0)
{
substr=(char**)realloc(substr,sizeof(*char)*(count+1));
*substr[count]=(char*)malloc(sizeof(char)*len);
strncpy(*substr[count],S+idx-len,len-1);
substr[count][len]='\0';
count++;
}
idx=idx+2;
len=0;
}
idx++;len++;
}
return substr;
}
size_t Tokenize(const string &src, const string &delim, vector<string> *tokens) {
tokens->clear();
string::size_type start;
string::size_type sep_pos;
for(start = 0; string::npos != (sep_pos = src.find(delim, start));
start = sep_pos + delim.size()) {
tokens->push_back(src.substr(start, sep_pos - start));
}
if(start < src.length()) {
tokens->push_back(src.substr(start));
}
return tokens->size();
}
token string match. O(mn) so is this the way to do this?
- nunbit romance April 04, 2007