一.题目
给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串 s
,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
- 每个右括号都有一个对应的相同类型的左括号。
示例 1:
输入:s = "()"
输出:true
示例 2:
输入:s = "()[]{}"
输出:true
示例 3:
输入:s = "(]"
输出:false
示例 4:
输入:s = "([])"
输出:true
二.代码
bool isValid(char* s)
{ char a[100000]="\0";if((s[0]==')')||(s[0]=='}')||(s[0]==']')){return false;}int i,j=0;for(i=0;i<strlen(s);i++){if((s[i]=='(')||(s[i]=='{')||(s[i]=='[')){a[j]=s[i];j++;}if((s[i]==')')||(s[i]=='}')||(s[i]==']')){if(j>0){j--;}else{return false;}switch(s[i]){case ')':{if(a[j]=='('){a[j]='\0';}else{return false;}break;}case '}':{if(a[j]=='{'){a[j]='\0';}else{return false;}break;}case ']':{if(a[j]=='['){a[j]='\0';}else{return false;}break;}}}continue;}if(a[0]!='\0'){return false;}else{return true;}
}
三.补全代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>bool isValid(char* s)
{int len = strlen(s);char* a = (char*)malloc(len + 1);if (a == NULL) {// 处理内存分配失败的情况perror("malloc failed");exit(EXIT_FAILURE);}a[0] = '\0';if ((s[0] == ')') || (s[0] == '}') || (s[0] == ']')){free(a);return false;}int i, j = 0;for (i = 0; i < len; i++){if ((s[i] == '(') || (s[i] == '{') || (s[i] == '[')){j++;a[j - 1] = s[i];}if ((s[i] == ')') || (s[i] == '}') || (s[i] == ']')){if (j > 0){j--;switch (s[i]){case ')':if (a[j] == '('){a[j] = '\0';}else{free(a);return false;}break;case '}':if (a[j] == '{'){a[j] = '\0';}else{free(a);return false;}break;case ']':if (a[j] == '['){a[j] = '\0';}else{free(a);return false;}break;}}else{free(a);return false;}}}bool valid = (a[0] == '\0');free(a);return valid;
}int main() {char* str = "()[]{}";if (isValid(str)) {printf("Valid\n");}else {printf("Invalid\n");}return 0;
}