假设以'I' 和 'O' 分别表示进栈和出栈操作,栈的初态和终态均为空,进栈和出栈的操作序列str可表示为仅由'I' 和 'O' 组成的字符串。设计一个算法判定str是否合法。

以下是一个简单的Java代码实现:

import java.util.Stack;

public class StackOperationChecker {
    public static boolean isValidStackOperation(String str) {
        Stack<Character> stack = new Stack<>();

        for (int i = 0; i < str.length(); i++) {
            char operation = str.charAt(i);

            if (operation == 'I') {
                stack.push(operation);
            } else if (operation == 'O') {
                if (stack.isEmpty()) {
                    return false; // 出栈操作时栈为空,不合法
                }
                stack.pop();
            } else {
                return false; // 字符串包含非法字符
            }
        }

        return stack.isEmpty(); // 所有操作执行完毕后,栈应为空
    }

    public static void main(String[] args) {
        String str1 = "IOIOIO";
        String str2 = "IOOIIO";
        String str3 = "IOIIOO";

        System.out.println(isValidStackOperation(str1)); // 输出 true
        System.out.println(isValidStackOperation(str2)); // 输出 false
        System.out.println(isValidStackOperation(str3)); // 输出 false
    }
}

该代码创建了一个栈对象stack,然后遍历输入字符串str中的每个字符。如果字符为'I',则将其压入栈中;如果字符为'O',则判断栈是否为空,如果为空则返回false,否则将栈顶元素弹出。如果字符串包含其他字符,则直接返回false

最后,判断所有操作执行完毕后,栈是否为空。如果为空,则返回true,否则返回false

栈操作序列合法性判定算法及Java实现

原文地址: http://www.cveoy.top/t/topic/pjfB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录