Leetcode 1544. Make String Great

Intuition

Use two pointers to iterate through the string checking each adjacent character to see if it is "bad" or "good".

Approach

First if the string is 1 or fewer characters we know it is good so we can just return it.

If that's not the case, we change it to an array and then to a list so we can dynamically resize it.

Then while p2 is less than the count of the list, we just iterate through and using the ASCII values, check to see if the two characters are bad. If they are, we remove them from the list and reset out pointers. If they are good, we just increment the pointers.

Finally when we reach the end of the list we return the remaining string.

Code

public class Solution 
{
    public string MakeGood(string s) 
    {
        if(s.Length == 0 || s.Length == 1)
        {
            return s;
        }
        //convert string to list
        var arr = s.ToCharArray();
        var list = new List<char>(arr);
        //iterate through string with 2 pointers
        var p1 = 0;
        var p2 = 1;
        while(p2 < list.Count)
        {
            var num1 = list[p1];
            var num2 = list[p2];
            //check if adjacent characters are bad
            if(Math.Abs(num1 - num2) == 32)
            {
                //if so remove them and reset pointers
                list.RemoveRange(p1, 2);
                p1 = 0;
                p2 = 1;        
            }
            else
            {
                p1 = p2;
                p2++;
            }           
        }

        return new string(list.ToArray());
    }
}