I'm a beginner programmer that is learning C and I'm doing some exercises on LeetCode but I ran with a problem with today's problem, I'm going to put the problem bellow but my difficult is on a do while loop that I did to loop the deleting function if there are adjacent duplicates, my code can delete the duplicates on the first iteration, but it's not looping to do any subsequent tasks, if anyone could help my I would be grateful.
The LeetCode Daily Problem (10/11/2022):
You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.
We repeatedly make duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.
Example 1:
Input: s = "abbaca" Output: "ca" Explanation: For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".
Example 2:
Input: s = "azxxzy" Output: "ay"
Constraints:
1 <= s.length <= 105 s consists of lowercase English letters.
My code (testcase: "abbaca"):
char res[100]; //awnser
char * removeDuplicates(char * s){
//int that verifies if any char from the string can be deleted
int ver = 0;
//do while loop that reiterates to eliminate the duplicates
do {
int lenght = strlen(s);
int j = 0;
int ver = 0;
//for loop that if there are duplicates adds one to ver and deletes the duplicate
for (int i = 0; i < lenght ; i ){
if (s[i] == s[i 1]){
i ;
j--;
ver ;
}
else {
res[j] = s[i];
}
j ;
}
//copying the res string into the s to redo the loop if necessary
strcpy(s,res);
} while (ver > 0);
return res;
}
The fuction returns "aaca". I did some tweaking with the code and found that after the loop the ver variable always return to 0, but I don't know why.
CodePudding user response:
I see two errors
res
isn't terminated so thestrcpy
may fail- You have two definitions of
int ver
so the one being incremented is not the one being checked bywhile (ver > 0);
In other words: The do-while only executes once.
Based on your code it can be fixed like:
char res[100]; //awnser
char * removeDuplicates(char * s){
//int that verifies if any char from the string can be deleted
int ver = 0;
//do while loop that reiterates to eliminate the duplicates
do {
int lenght = strlen(s);
int j = 0;
ver = 0; // <--------------- Changed
//for loop that if there are duplicates adds one to ver and deletes the duplicate
for (int i = 0; i < lenght ; i ){
if (s[i] == s[i 1]){
i ;
j--;
ver ;
}
else {
res[j] = s[i];
}
j ;
}
res[j] = '\0'; // <---------------- Changed
//copying the res string into the s to redo the loop if necessary
strcpy(s,res);
} while (ver > 0);
return res;
}