Untitled

 avatar
unknown
plain_text
2 months ago
1.8 kB
2
Indexable
import java.util.Stack;

public class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();

        // Traverse each character in the string
        for (char c : s.toCharArray()) {
            stack.push(c);

            // Check if the last three characters in the stack form "abc"
            if (stack.size() >= 3) {
                char third = stack.pop();
                char second = stack.pop();
                char first = stack.pop();

                // If the last three characters do not form "abc", push them back
                if (first != 'a' || second != 'b' || third != 'c') {
                    stack.push(first);
                    stack.push(second);
                    stack.push(third);
                }
            }
        }

        // If the stack is empty, the string is valid
        return stack.isEmpty();
    }
}



public class Solution {
    public boolean isValid(String s) {
        // Use a stack to simulate the construction of the string
        StringBuilder stack = new StringBuilder();

        // Traverse each character in the string
        for (char c : s.toCharArray()) {
            // Append the character to the stack
            stack.append(c);

            // Check if the last three characters form "abc"
            if (stack.length() >= 3 &&
                stack.charAt(stack.length() - 3) == 'a' &&
                stack.charAt(stack.length() - 2) == 'b' &&
                stack.charAt(stack.length() - 1) == 'c') {
                // Remove the last three characters
                stack.setLength(stack.length() - 3);
            }
        }

        // If the stack is empty, the string is valid
        return stack.length() == 0;
    }
}
Editor is loading...
Leave a Comment