LeetCode Exercise

Logo

This is my LeetCode exercise.
You can see all question I did here.

View the Project on GitHub YaoyuanHsu/LeetCode_Exercise

tags: leetcode easy string stack

1544. Make The String Great

Description

Given a string s of lower and upper case English letters.

A good string is a string which doesn’t have two adjacent characters s[i] and s[i + 1] where:

Return the string after making it good. The answer is guaranteed to be unique under the given constraints.

Notice that an empty string is also good.

Examples

Example 1:

Input: s = “leEeetcode”
Output: “leetcode”
Explanation: In the first step, either you choose i = 1 or i = 2, both will result “leEeetcode” to be reduced to “leetcode”.

Example 2:

Input: s = “abBAcC”
Output: “”
Explanation: We have many possible scenarios, and all lead to the same answer. For example:
“abBAcC” –> “aAcC” –> “cC” –> “”
“abBAcC” –> “abBA” –> “aA” –> “”

Example 3:

Input: s = “s”
Output: “s”

Constraints:

Code

char * makeGood(char * s){
    int length = strlen(s);
    //If input is too short, just return
    if( (length <= 1) )
        return s;
    //Linear search for bad case and modify it
    restart:
    length = strlen(s);
    for(int i = 0 ; i < length - 1 ; i++){
        if ( (s[i] == s[i+1] + 32) || (s[i] == s[i+1] - 32) ){
            for(; i < length - 2; i++)
                s[i] = s[i + 2];
            s[length - 2] = '\0';
            s = (char *)realloc(s, (length - 1) * sizeof(char));
            goto restart;
        }
    }
    return s;
}

Complexity

Space Time
$O(1)$ $O(N^2)$

Result

Notes