20. Valid Parentheses (E)

Valid Parentheses (E)

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "([)]"
Output: false

题意

给定一个只包含括号的字符串,判断括号是否匹配。

思路

用栈处理:是左半边括号则压入栈,是右半边括号则比较与栈顶是否匹配。最后检查栈是否清空。


代码实现

class Solution {
    public boolean isValid(String s) {
        Deque<Character> stack = new ArrayDeque<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(' || c == '[' || c == '{') {
                stack.push(c);
            } else if (c == ')') {
                if (!stack.isEmpty() && stack.peek() == '(') {
                    stack.pop();
                } else {
                    return false;
                }
            } else if (c == ']') {
                if (!stack.isEmpty() && stack.peek() == '[') {
                    stack.pop();
                } else {
                    return false;
                }
            } else {
                if (!stack.isEmpty() && stack.peek() == '{') {
                    stack.pop();
                } else {
                    return false;
                }
                    
            }
        }
        return stack.isEmpty();
    }
}
/** * 表单处理与验证模块 - 集中管理所有表单相关逻辑 */ const FormHandler = { /** * 通用表单提交处理函数 * @param {string} formId - 表单元素的ID * @param {string} url - 提交表单的目标URL * @param {function} successCallback - 成功回调函数 * @param {function} errorCallback - 失败回调函数 */ handleFormSubmit(formId, url, successCallback, errorCallback) { const form = document.getElementById(formId); if (!form) { console.error(`未找到表单元素: ${formId}`); return; } form.addEventListener('submit', (e) => { e.preventDefault(); // 获取提交按钮并显示加载状态 const submitButton = form.querySelector('button[type="submit"]'); const originalText = submitButton?.innerHTML || '提交'; if (submitButton) { submitButton.disabled = true; submitButton.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i>处理中...'; } // 表单验证 let isValid = true; const inputs = form.querySelectorAll('input[required]'); inputs.forEach(input => { const errorElement = document.getElementById(`${input.id}Error`); if (errorElement) { errorElement.classList.add('hidden'); } // 检查必填字段是否为空 if (!input.value.trim()) { isValid = false; if (errorElement) { errorElement.textContent = `请输入${input.placeholder}`; errorElement.classList.remove('hidden'); } } }); // 如果验证失败,恢复按钮状态并返回 if (!isValid) { if (submitButton) { submitButton.disabled = false; submitButton.innerHTML = originalText; } return; } // 构建表单数据并发送请求 const formData = new FormData(form); fetch(url, { method: 'POST', body: formData }) .then(response => { if (!response.ok) { throw new Error('服务器响应错误'); } return response.json(); }) .then(data => { if (data.success) { // 邮箱验证成功后的特殊处理 if (formId === 'verify_email' && data.redirect_url) { this.showNotification('success', data.message); setTimeout(() => { window.location.href = data.redirect_url; }, 2000); } else { // 执行成功回调 if (typeof successCallback === 'function') { successCallback(data); } } } else { // 执行失败回调 if (typeof errorCallback === 'function') { errorCallback(data); } else { this.showNotification('error', data.message || '操作失败,请重试'); } } }) .catch(error => { console.error('请求出错:', error); this.showNotification('error', '网络错误,请稍后重试'); }) .finally(() => { // 恢复按钮状态 if (submitButton) { submitButton.disabled = false; submitButton.innerHTML = originalText; } }); }); }, /** * 处理登录表单提交 */ handleLoginForm() { this.handleFormSubmit('loginForm', '{{ url_for('login') }}', // 登录成功回调函数 (data) => { this.showNotification('success', data.message); setTimeout(() => { window.location.href = '{{ url_for('index') }}'; }, 1500); }, // 登录失败回调函数 (data) => { const messageElement = document.getElementById('loginMessage'); if (messageElement) { messageElement.textContent = data.message; messageElement.classList.remove('hidden', 'success-message'); messageElement.classList.add('error-message'); } else { this.showNotification('error', data.message); } } ); }, /** * 处理注册表单提交 */ handleRegisterForm() { this.handleFormSubmit('registerForm', '{{ url_for('register') }}', (data) => { this.showNotification('success', data.message); }, (data) => { const messageElement = document.getElementById('registerMessage'); if (messageElement) { messageElement.textContent = data.message; messageElement.classList.remove('hidden', 'success-message'); messageElement.classList.add('error-message'); } else { this.showNotification('error', data.message); } } ); }, /** * 处理忘记密码表单提交 */ handleForgotPasswordForm() { this.handleFormSubmit('forgotPasswordForm', '{{ url_for('forgot_password') }}', (data) => { this.showNotification('success', data.message); }, (data) => { const messageElement = document.getElementById('forgotPasswordMessage'); if (messageElement) { messageElement.textContent = data.message; messageElement.classList.remove('hidden', 'success-message'); messageElement.classList.add('error-message'); } else { this.showNotification('error', data.message); } } ); }, /** * 处理重置密码表单提交 */ handleResetPasswordForm() { this.handleFormSubmit('resetPasswordForm', '', (data) => { this.showNotification('success', data.message); setTimeout(() => { window.location.href = '{{ url_for('login') }}'; }, 2000); }, (data) => { const messageElement = document.getElementById('resetPasswordMessage'); if (messageElement) { messageElement.textContent = data.message; messageElement.classList.remove('hidden', 'success-message'); messageElement.classList.add('error-message'); } else { this.showNotification('error', data.message); } } ); }, /** * 检查邮箱验证结果 */ checkVerificationResult() { const urlParams = new URLSearchParams(window.location.search); const success = urlParams.get('success'); const message = decodeURIComponent(urlParams.get('message') || ''); if (success && message) { const type = success === 'true' ? 'success' : 'error'; this.showNotification(type, message); history.replaceState({}, document.title, window.location.pathname); } }, /** * 处理重置密码链接 */ handleResetPasswordLink() { const urlParams = new URLSearchParams(window.location.search); const token = urlParams.get('token'); if (token) { document.getElementById('resetToken').value = token; this.openModal('reset-password'); } }, /** * 检查重置密码令牌 */ checkResetToken() { const urlParams = new URLSearchParams(window.location.search); const token = urlParams.get('token'); if (token) { document.getElementById('resetToken').value = token; } }, /** * 打开模态框 */ openModal(modalId) { const modal = document.getElementById(modalId); if (modal) { modal.classList.remove('hidden'); modal.classList.add('flex'); // 假设存在背景遮罩 const backdrop = modal.querySelector('.backdrop'); if (backdrop) { backdrop.classList.remove('hidden'); } } }, /** * 显示通知(若notification.js未加载的备用方案) */ showNotification(type, message) { if (window.showNotification) { window.showNotification(type, message); // 优先使用外部通知函数 } else { console.log(`[通知] ${type}: ${message}`); // 备用日志输出 } }, /** * 处理搜索表单提交 */ handleSearchFormSubmit() { const searchForm = document.getElementById('searchForm'); if (searchForm) { searchForm.addEventListener('submit', (e) => { e.preventDefault(); const keyword = document.querySelector('input[name="keyword"]').value; window.location.href = `{{ url_for('search_result') }}?keyword=${encodeURIComponent(keyword)}`; }); } }, /** * 初始化所有功能 */ init() { this.checkResetToken(); this.checkVerificationResult(); this.handleResetPasswordLink(); // 初始化表单处理 this.handleLoginForm(); this.handleRegisterForm(); this.handleForgotPasswordForm(); this.handleResetPasswordForm(); // 处理搜索表单 this.handleSearchFormSubmit(); } }; // 模块化导出 - 兼容Node.js和浏览器环境 if (typeof module !== 'undefined' && module.exports) { module.exports = FormHandler; } else { window.FormHandler = FormHandler; // 浏览器环境暴露为全局对象 } console.log('FormHandler 模块已加载'); console.log('FormHandler 对象:', FormHandler); 帮我看看哪里少括号了
06-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值