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();
    }
}
/***************************************************************************** * * This file is copyright (c) 2023 PTC, Inc. * All rights reserved. * * Name: HTTP-profile * Description: A simple HTTP example profile that queries weather data * from a weather REST-API. * Version: 0.3.0 * Revision history: * 0.3.0 Added bulkId property to the Tag object. * Added quality property to the CompleteTag object. * Added bulkId property to the OnValidateTagResult. ******************************************************************************/ /** * @typedef {string} MessageType - Type of communication "Read", "Write". */ /** * @typedef {string} DataType - KEPServerEx datatype "Default", "String", "Boolean", "Char", "Byte", "Short", "Word", "Long", "DWord", "Float", "Double", "BCD", "LBCD", "Date", "LLong", "QWord". */ /** * @typedef {number[]} Data - Array of data bytes. Uint8 byte array. */ /** * @typedef {object} Tag * @property {string} Tag.address - Tag address. * @property {DataType} Tag.dataType - Kepserver data type. * @property {boolean} Tag.readOnly - Indicates permitted communication mode. * @property {integer} Tag.bulkId - Integer that identifies the group into which to bulk the tag with other tags. */ /** * @typedef {object} CompleteTag * @property {string} Tag.address - Tag address. * @property {*} Tag.value - (optional) Tag value. * @property {string} Tag.quality - (optional) Tag quality "Good", "Bad", or "Uncertain". */ /** * @typedef {object} OnProfileLoadResult * @property {string} version - Version of the driver. * @property {string} mode - Operation mode of the driver "Client", "Server". */ /** * @typedef {object} OnValidateTagResult * @property {string} address - (optional) Fixed up tag address. * @property {DataType} dataType - (optional) Fixed up Kepserver data type. Required if input dataType is "Default". * @property {boolean} readOnly - (optional) Fixed up permitted communication mode. * @property {integer} bulkId - (optional) Integer that identifies the group into which to bulk the tag with other tags. * Universal Device Driver assigns the next available bulkId, if undefined. If defined for one tag, * must define for all tags. * @property {boolean} valid - Indicates address validity. */ /** * @typedef {object} OnTransactionResult * @property {string} action - Action of the operation: "Complete", "Receive", "Fail". * @property {CompleteTag[]} tags - Array of tags (if any active) to complete. Undefined indicates tag is not complete. * @property {Data} data - The resulting data (if any) to send. Undefined indicates no data to send. */ /** Global variable for driver version */ const VERSION = "2.0"; /** Global variable for driver mode */ const MODE = "Client" /** Global variable for action */ const ACTIONCOMPLETE = "Complete" const ACTIONFAILURE = "Fail" const ACTIONRECEIVE = "Receive" /** Global variables for communication modes used in transactions */ const READ = "Read" const WRITE = "Write" /** * Retrieve driver metadata. * * @return {OnProfileLoadResult} - Driver metadata. */ function onProfileLoad() { return { version: VERSION, mode: MODE }; } /** * Validate an address. * * @param {object} info - Object containing the function arguments. * @param {Tag} info.tag - Single tag. * * @return {OnValidateTagResult} - Single tag with a populated '.valid' field set. * * * Unlike physical devices an address doesn't mean anything for the http protocol * However, we can still use this function to our advantage. The HTTP GET request * returns a JSON object. We can use this object to return multiple tag values. * Example JSON: * { * "visibility": 1000 * "wind": { * "speed": 8.38 * "direction": "north" * } * "weather": [ * { * "main": "sunny" * "description": "partly sunny" * } * { * "main": "sunny" * "description": "mostly sunny" * } * ] * } * * There are three types of addresses we can allow in this case * 1. <key> ex. Tag address = “visibility” * 2. <key>:<value> ex. Tag address = “wind:speed” * 3. <key>[<index>]:<value> ex. Tag address = “weather[0]:main” * * We will use this address to help parse the data in onData */ function onValidateTag(info) { // Format the address for validation info.tag.address = info.tag.address.toLowerCase(); /* * The regular expression to compare address to. * ^, & Starting and ending anchors respectively. The match must occur between the two anchors * [a-z]+ At least 1 or more characters between 'a' and 'z' * [0-9]+ At least 1 or more digits between 0 and 9 * ()? Whatever is in the parentheses can appear 0 or 1 times */ let regex = /^[a-z]+(\[[0-9]+\]:[a-z]+$)?(:[a-z]+)?$/; try { // Validate the address against the regular expression if (regex.test(info.tag.address)) { info.tag.valid = true; } else { info.tag.valid = false; } return info.tag } catch (e) { // Use log to provide helpful information that can assist with error resolution log("Unexpected error (onValidateTag): " + e.message); info.tag.valid = false; return info.tag; } } /** * Handle request for a tag to be completed. * * @param {object} info - Object containing the function arguments. * @param {MessageType} info.type - Communication mode for tags. Can be undefined. * @param {Tag[]} info.tags - Tags currently being processed. Can be undefined. * * @return {OnTransactionResult} - The action to take, tags to complete (if any) and/or data to send (if any). */ function onTagsRequest(info) { // Writes are not permitted if (info.type === WRITE){ return {action: ACTIONFAILURE} // data field not needed in "Failure" case } // Build the request as a string let host = "192.241.169.168"; // IP address of api.openweathermap.org // TODO: Fill in the two lines below. See README.md for details let zip = "{{ZIP_CODE}}"; // Zip code let appId = "{{API_KEY}}"; // API key let request = "GET http://" + host + "/data/2.5/weather?APPID=" + appId + "&zip=" + zip + ",us HTTP/1.1\r\n"; request += "Host: " + host + "\r\n"; request += "\r\n"; // Convert string to bytes let readData = stringToBytes(request); return { action: ACTIONRECEIVE, data: readData }; } /** * Handle incoming data. * * @param {object} info - Object containing the function arguments. * @param {MessageType} info.type - Communication mode for tags. Can be undefined. * @param {Tag[]} info.tags - Tags currently being processed. Can be undefined. * @param {Data} info.data - The incoming data. * * @return {OnTransactionResult} - The action to take, tags to complete (if any) and/or data to send (if any). */ function onData(info) { // Writes are not permitted if (info.type === WRITE){ return {action: ACTIONFAILURE} // tags field not needed in "Failure" case } // Convert the response to a string let stringResponse = ""; for (let i = 0; i < info.data.length; i++) { stringResponse += String.fromCharCode(info.data[i]); } // Get the JSON body of the response let jsonStr = stringResponse.substring(stringResponse.indexOf('{'), stringResponse.lastIndexOf('}') + 1 ); log(`JsonSubstr: ${jsonStr}`) // Parse the JSON string let jsonObj = JSON.parse(jsonStr); // Array to hold tag values let values = []; let action = ACTIONFAILURE; // Evaluate each tag's address and get the JSON value info.tags.forEach(function (tag) { let case1 = /^[a-z]+$/; // Example: Tag address matches "visibility" let case2 = /^[a-z]+:[a-z]+$/; // Example: Tag address matches "wind:speed" let case3 = /^[a-z]+\[[0-9]+\]:[a-z]+$/; // Example: Tag address matches "forecast[0]:main" // let tagValue = null; tag.value = null; if (case1.test(tag.address)) { // Get the JSON values from the provided key tag.value = jsonObj[tag.address]; } else if (case2.test(tag.address)) { // Split the address at the colon let keyValuePair = tag.address.split(':'); // Get the value by parsing the JSON with the Parent key and child key let parentValue = jsonObj[keyValuePair[0]]; tag.value = parentValue[keyValuePair[1]]; } else if (case3.test(tag.address)) { // Get the key value pair as well as the index let keyValuePair = tag.address.split(':'); let parentKey = keyValuePair[0].split('['); let index = parentKey[1].replace(']', ''); // Get the value by parsing the JSON with the Parent key, index and child key let parentValue = jsonObj[parentKey[0]][index]; tag.value = parentValue[keyValuePair[1]]; } // Determine if all tags were parsed successfully if (tag.value != undefined || tag.value != null) { action = ACTIONCOMPLETE; } }); log(JSON.stringify(info.tags)) return { action: action, tags: info.tags }; } /** * Helper function to translate string to bytes. * Required. * * @param {string} str * @return {Data} */ function stringToBytes(str) { let byteArray = []; for (let i = 0; i < str.length; i++) { let char = str.charCodeAt(i) & 0xFF; byteArray.push(char); } // return an array of bytes return byteArray; } 以上案例代码中onProfileLoad 、onValidateTag 、onTagsRequest 、onData、stringToBytes  函数名都是核心函数 分析核心函数 的作用,同时替换案例 的API 并适配了新的数据格式 : 新API地址:http://192.168.17.201:39320/?read=Test.AutoWash.HD1 新API 数据返回 格式 :{"message":"欢迎来到 OPC UA Web 服务"} Tag :取 message 字段 API 没有API_KEY ,可直接 GET 访问就有返回格式, 保留了案例代码 的核心函数结构, 输出JavaScript 代码 。再事整体检查可行性、验证结果 输出完整的 JavaScript 代码。
10-14
下载方式:https://renmaiwang.cn/s/t0445 在时序发生器设计实验中,如何达成T4至T1的生成? 时序发生器的构建可以通过运用一个4位循环移位寄存器来达成T4至T1的输出。 具体而言:- **CLR(清除)**: 作为全局清零信号,当CLR呈现低电平状态时,所有输出(涵盖T1至T4)皆会被清除。 - **STOP**: 在T4脉冲的下降沿时刻,若STOP信号处于低电平状态,则T1至T4会被重置。 - **启动流程**: 当启动信号START处于高电平,并且STOP为高电平时,移位寄存器将在每个时钟的上升沿向左移动一位。 移位寄存器的输出端对应了T4、T3、T2、T1。 #### 2. 时序发生器如何调控T1至T4的波形形态? 时序发生器通过以下几个信号调控T1至T4的波形形态:- **CLR**: 当CLR处于低电平状态时,所有输出均会被清零。 - **STOP**: 若STOP信号为低电平,且在T4脉冲的下降沿时刻,所有输出同样会被清零。 - **START**: 在START信号有效(通常为高电平),并且STOP为高电平时,移位寄存器启动,从而产生环形脉冲输出。 ### 微程序控制器实验#### 3. 微程序控制器实验中的四条机器指令及其对应的微程序段指定的机器指令及其关联的微程序段如下:- **NOP**: 00- **R0->B**: 04- **A+B->R0**: 05- **P<1>**: 30- **IN->R0**: 32- **R0->OUT**: 33- **HLT**: 35#### 4. 微程序段中的微操作/微命令序列针对每条微指令,其对应的微操作或微命令序列如下:- **IN->R0**: 输入(IN)单元的数据被...
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值