过程中使用了栈。
#include "stdbool.h" #define NULL ((void *)0) bool isValid(char * s){ int len = strlen(s); char p[len]; int j=0; int i; if (len <= 1) return false; for (i=0;i<len;i++){ if(s[i]==‘(‘ || s[i]==‘[‘ || s[i] == ‘{‘){ p[j++]=s[i]; } else{ if (j==0 || !((s[i]==‘)‘&&p[j-1]==‘(‘) ||(s[i]==‘]‘&&p[j-1]==‘[‘)||(s[i]==‘}‘&&p[j-1]==‘{‘))) return false; else j--; } } return j==0; }
第一次用了0ms,记录一下。
用了string.replace(),代码比较简洁,性能上肯定不如C语言。
class Solution: def isValid(self, s: str) -> bool: while ‘{}‘ in s or ‘()‘ in s or ‘[]‘ in s: s=s.replace(‘{}‘,‘‘).replace(‘()‘,‘‘).replace(‘[]‘,‘‘) return s==‘‘
心血来潮的用了一次C#,惊讶于性能竟然不如Python 3。
public class Solution { public bool IsValid(string s) { while(s.Contains("()") || s.Contains("[]") || s.Contains("{}")) s = s.Replace("()","").Replace("[]","").Replace("{}",""); return s == ""; } }
每日LeetCode - 20. 有效的括号(C语言、Python 3和C#)
原文:https://www.cnblogs.com/vicky2021/p/14743035.html