英文:
Given a string s that contains only '(', ')', '{', '}', '[', ']', determine whether the string is valid
问题
Here's the translated portion of your text without the code:
我想要编写一个函数,该函数执行以下操作:给定一个只包含'(', ')', '{', '}', '[', ']'的字符串s,确定该字符串是否有效。有效的字符串需要满足以下条件:
- 开括号必须用相同类型的闭括号关闭。
- 开括号必须按照正确的顺序关闭。
- 每个闭括号都必须有相应类型的开括号。
示例:
输入:s = "()"
输出:true
输入:s = "()[]{}"
输出:true
输入:s = "(]"
输出:false。
但是当我测试代码时:
输入 "()"
输出显示为 false。
这是我的代码。
代码部分不要翻译,只返回翻译好的部分。如果您有关于代码的问题,请随时提出。
英文:
I want to write a function that does the following: Given a string s that contains only '(', ')', '{', '}', '[', ']', determine whether the string is valid. A valid string needs to satisfy:
- the opening parenthesis must be closed with the same type of closing parenthesis.
- Opening parentheses must be closed in the correct order.
- Each closing parenthesis has a corresponding opening parenthesis of the same type.
Example:
Input: s = "()"
Output: true
Input: s = "()[]{}"
Output: true
Input: s = "(]"
Output: false.
But when I test the code with:
Input "()"
Output is showing as false.
Here is my code.
import java.util.HashMap;
import java.util.Map;
class Solution {
public boolean isValid(String s) {
Map<String, String> map = Map.of("(",")","[","]","{","}");
if (s.length() % 2 != 0) {
return false;
}
for (int index = 0; index < s.length() / 2; index++) {
if (!map.containsKey(s.charAt(2 * index + 1))) {
return false;
} else {
if (!map.get(s.charAt(2 * index + 1)).equals(s.charAt(2 * index + 2))) {
return false;
}
}
}
return true;
}
}
The function may be realized by using the stack, but the first thing I thought of was my method. Where is the logic error in my method?
答案1
得分: 2
看起来你有2个问题:
-
你的代码假设
charAt()
接受从1开始的索引值。实际上不是这样的 - 它接受从0开始的值。 -
你的代码假设没有嵌套。因此,对于像
[()]
这样的情况不起作用。
英文:
Looks like you have 2 issues:
-
Your code assumes
charAt()
takes index values from 1 onwards. It does not - it takes values from 0 -
Your code assumes there is no nesting. So, it won't work for cases like
[()]
答案2
得分: 0
第一个回答中没有解决的另一个问题是,您试图使用char
来访问Map<String, String>
。charAt()
返回一个字符,而映射中的键是字符串。可以通过将映射更新为Map<Character, Character>
来解决此问题,或者在获取特定索引处的字符时获取字符的字符串值(例如使用String.valueOf()
)。
这与Abdeali的回答中提出的问题一起解决,应该能解决您的问题。
英文:
One additional issue that is not addressed in the first answer is that you are attempting to access a Map<String, String>
with a char
. charAt()
returns a character and the keys in the map are strings. This can be fixed by updating the map to be Map<Character, Character>
, or by getting the string value of the character (such as by using String.valueOf()
) wherever you are getting the character at a certain index.
This combined with addressing the issues laid out in Abdeali's answer should fix your issue.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论