Backspace String Compare
Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.
Sample input 1 : S = "ab#c" T = "ad#c"
Sample output 1 : True
Explanation : Both S and T become "ac"
Sample input 2 : S = "a#c" T = "b"
Sample output 2 : False
Explanation : S become "c" but T become "b"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | #include <stdio.h> #include<string.h> char stack[100]; int top=-1; //push character in to stack void push(char cha) { top++; stack[top]=cha; } //pop character from stack int pop() { stack[top]='\0'; //set empty character top--; if(top<-1) //this is incase ##abc { //if two ## come at the beginning top=-1; } } int main() { char str1[20],str2[20]; int len1,len2,i,j; gets(str1); gets(str2); len1=strlen(str1); len2=strlen(str2); for(i=0;i<len1;i++) { if(str1[i]=='#') { pop(); } else { push(str1[i]); } } strcpy(str1,stack); top=-1;//reset the stack for(j=0;j<len2;j++) { if(str2[j]=='#') { pop(); } else { push(str2[j]); } } strcpy(str2,stack); if(strcmp(str2,str1)==0) { printf("True ( %s == %s )",str1,str2); } else { printf("False ( %s != %s )",str1,str2); } return 0; } |
OUTPUT :
0 comments