Remove All Adjacent Duplicates in String LeetCode (Adjacent Character Remove)

Given a string, complete the given function to recursively remove the adjacent duplicate characters and return the resultant string. 

If there are no characters left in the resultant string, return "-1" (without quotes). 

Sample Test Cases 

Sample Input: ABCCBCBA 

Output: ACBA 

Explanation: (ABCCBCBA --> ABBCBA --> ACBA) 

Sample Input: AA 

Sample Output: -1 

 Solution 1:

 1)Use two pointers p1 pointing to first char and p2 to the second char

 2)Repeat the following till p2 reaches the end or the length of string is zero

 2 a)if char[p1]==char[p2], update the string by removing these chars, re-assign p1 to 0 and p2 to 1

 2 b) if (a) is false advance p1 and p2

 Complexity: O(n)

This is an interesting problem that is well discussed in LeetCode and GeeksForGeeks

No comments:

Post a Comment