Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/1003.html

1003. Check If Word Is Valid After Substitutions (Medium)

Given a string s, determine if it is valid.

A string s is valid if, starting with an empty string t = "", you can transform t into s after performing the following operation any number of times:

  • Insert string "abc" into any position in t. More formally, t becomes tleft + "abc" + tright, where t == tleft + tright. Note that tleft and tright may be empty.

Return true if s is a valid string, otherwise, return false.

 

Example 1:

Input: s = "aabcbc"
Output: true
Explanation:
"" -> "abc" -> "aabcbc"
Thus, "aabcbc" is valid.

Example 2:

Input: s = "abcabcababcc"
Output: true
Explanation:
"" -> "abc" -> "abcabc" -> "abcabcabc" -> "abcabcababcc"
Thus, "abcabcababcc" is valid.

Example 3:

Input: s = "abccba"
Output: false
Explanation: It is impossible to get "abccba" using the operation.

Example 4:

Input: s = "cababc"
Output: false
Explanation: It is impossible to get "cababc" using the operation.

 

Constraints:

  • 1 <= s.length <= 2 * 104
  • s consists of letters 'a', 'b', and 'c'

Related Topics:
String, Stack

Similar Questions:

Solution 1.

j is read pointer and i is write pointer. We always write s[j] to s[i].

If the last 3 characters in front of i is abc, we clean them by i -= 3.

In the end, return i == 0.

// OJ: https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/
// Time: O(N)
// Space: O(1)
class Solution {
public:
    bool isValid(string s) {
        int i = 0, N = s.size();
        for (int j = 0; j < N; ++j) {
            s[i++] = s[j];
            if (i >= 3 && s[i - 3] == 'a' && s[i - 2] == 'b' && s[i - 1] == 'c') i -= 3;
        }
        return i == 0;
    }
};
  • class Solution {
        public boolean isValid(String S) {
            Stack<Character> stack = new Stack<Character>();
            int length = S.length();
            for (int i = 0; i < length; i++) {
                char c = S.charAt(i);
                if (c == 'a' || c == 'b')
                    stack.push(c);
                else {
                    if (stack.size() < 2)
                        return false;
                    char c2 = stack.pop();
                    char c1 = stack.pop();
                    if (c2 != 'b' || c1 != 'a')
                        return false;
                }
            }
            return stack.isEmpty();
        }
    }
    
    ############
    
    class Solution {
        public boolean isValid(String s) {
            if (s.length() % 3 > 0) {
                return false;
            }
            StringBuilder stk = new StringBuilder();
            for (char c : s.toCharArray()) {
                int n = stk.length();
                if (c == 'c' && n > 1 && stk.charAt(n - 2) == 'a' && stk.charAt(n - 1) == 'b') {
                    stk.deleteCharAt(n - 1);
                    stk.deleteCharAt(n - 2);
                } else {
                    stk.append(c);
                }
            }
            return stk.length() == 0;
        }
    }
    
  • // OJ: https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/
    // Time: O(N)
    // Space: O(1)
    class Solution {
    public:
        bool isValid(string s) {
            int i = 0, N = s.size();
            for (int j = 0; j < N; ++j) {
                s[i++] = s[j];
                if (i >= 3 && s[i - 3] == 'a' && s[i - 2] == 'b' && s[i - 1] == 'c') i -= 3;
            }
            return i == 0;
        }
    };
    
  • class Solution:
        def isValid(self, s: str) -> bool:
            if len(s) % 3:
                return False
            stk = []
            for c in s:
                if c == 'c' and len(stk) > 1 and stk[-2] == 'a' and stk[-1] == 'b':
                    stk = stk[:-2]
                else:
                    stk.append(c)
            return not stk
    
    ############
    
    class Solution(object):
        def isValid(self, S):
            """
            :type S: str
            :rtype: bool
            """
            while "abc" in S:
                S = S.replace("abc", "")
            return not S
    
  • func isValid(s string) bool {
    	if len(s)%3 > 0 {
    		return false
    	}
    	stk := []rune{}
    	for _, c := range s {
    		n := len(stk)
    		if c == 'c' && n > 1 && stk[n-2] == 'a' && stk[n-1] == 'b' {
    			stk = stk[:n-2]
    		} else {
    			stk = append(stk, c)
    		}
    	}
    	return len(stk) == 0
    }
    
  • function isValid(s: string): boolean {
        if (s.length % 3 !== 0) {
            return false;
        }
        const t: string[] = [];
        for (const c of s) {
            t.push(c);
            if (t.slice(-3).join('') === 'abc') {
                t.splice(-3);
            }
        }
        return t.length === 0;
    }
    
    

All Problems

All Solutions