今天在codewar上做了这样一道题
In English and programming, groups can be made using symbols such as () and {} that change meaning. However, these groups must be closed in the correct order to maintain correct syntax.
Your job in this kata will be to make a program that checks a string for correct grouping. For instance, the following groups are done correctly:
({})
[]
[{()}]
The next are done incorrectly:{(})
([]
[])A correct string cannot close groups in the wrong order, open a group but fail to close it, or close a group before it is opened.
Your function will take an input string that may contain any of the symbols (), {} or [] to create groups.
It should return True if the string is empty or otherwise grouped correctly, or False if it is grouped incorrectly.
在我脑海中蹦出来的第一个想法就是使用栈来保存弹出,来判断括号是否匹配
我的程序
1 | public class Groups { |
边写边想,写的比较随意。
提交之后发现了一个简单至极的方案,完全不需要用栈来实现
1 |
|
我看到之后想简直太厉害了,几行代码就实现了,还没有那么复杂的判断,关键是纯String操作。
优雅!
我们的头脑遇到问题时会搜索一下有没有现成的解决方案,这在一定程度上减少了我们的脑力浪费,
但也有可能让我们丧失了创新的可能。遇事何不先问下自己还有其他的解决方案么?