力扣——Check If Word Is Valid After Substitutions

Check If Word Is Valid After Substitutions

Problem Description

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 t_left + "abc" + t_right, where t == t_left + t_right. Note that t_left and t_right 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.

Constraints:

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

Algorithm

The problem is the transform of the parenthesis matching.

The parenthesis matching is inserting "()" into the "()", while this one is inserting "abc" into the "abc". So the basical algorithm we use is same as the parenthesis matching (stack).

Code

class Solution {
public:
    bool isValid(string s) {
        stack<char>st;
        int n=s.size();
        char x,y;
        for(int i=0;i<n;i++){
            if(s[i]!='c'){
                st.push(s[i]);
            }else{
                if(st.size()>=2){
                    x=st.top();
                    st.pop();
                    y=st.top();
                    if(y=='a'&&x=='b'){
                        st.pop();
                    }else{
                        return false;
                    }
                }else{
                    return false;
                }
            }
        }
        return st.empty();
    }
};

猜你喜欢

转载自blog.csdn.net/qq_55126913/article/details/130469962
今日推荐