From e5ebc0c5339aa51875de8aa0053bb0ef30a50d19 Mon Sep 17 00:00:00 2001 From: juan Date: Sun, 5 Dec 2021 14:37:52 +0800 Subject: [PATCH] fix two answers to make them correct (100 pts.) --- .../pset12/{1-3-INCORRECT-GetVowel.c => 1-3-GetVowel.c} | 8 +++++--- semester1/pset12/2-1-paren.c | 9 +++++++-- 2 files changed, 12 insertions(+), 5 deletions(-) rename semester1/pset12/{1-3-INCORRECT-GetVowel.c => 1-3-GetVowel.c} (78%) diff --git a/semester1/pset12/1-3-INCORRECT-GetVowel.c b/semester1/pset12/1-3-GetVowel.c similarity index 78% rename from semester1/pset12/1-3-INCORRECT-GetVowel.c rename to semester1/pset12/1-3-GetVowel.c index 7670d77..66957c1 100644 --- a/semester1/pset12/1-3-INCORRECT-GetVowel.c +++ b/semester1/pset12/1-3-GetVowel.c @@ -1,5 +1,4 @@ // https://bbc3502.hopto.org/c2021/index.php/home-17/590-3 -/* ⚠*** This code is not perfect *** */ #include //将只包含小写字母的字符串str中的元音字母复制到字符数组vowel,并返回元音字符的个数。 @@ -23,14 +22,17 @@ int main() { #include #pragma GCC optimize("Ofast,inline") int getVowel(char str[], char vowel[]) { - char vowelstr[] = {'a', 'e', 'i', 'o', 'u', '\0'}; + char vowelstr[] = {'a', 'e', 'i', 'o', 'u'}; int len = 0; for (int i = 0, n = strlen(str); i < n; i++) { - for (int j = 0, m = strlen(vowelstr); j < m; j++) { + for (int j = 0, m = sizeof(vowelstr) / sizeof(char); j < m; j++) { if (vowelstr[j] == str[i]) { vowel[len++] = str[i]; } } } + // vowel[len] is a trash value, and will lead to undefined behavior in some + // cases + vowel[len] = '\0'; return len; } diff --git a/semester1/pset12/2-1-paren.c b/semester1/pset12/2-1-paren.c index 0a86695..4d301e2 100644 --- a/semester1/pset12/2-1-paren.c +++ b/semester1/pset12/2-1-paren.c @@ -11,9 +11,14 @@ int main(void) { // Process string int count = 0; - for (int i = 0, n = strlen(str); i < n; i++) { + int mismatch = 0; + for (int i = 0, n = strlen(str); i < n && !mismatch; i++) { if (str[i] == '(') { - count++; + if (count < 0) { // )( + mismatch = 1; + } else { + count++; + } } else if (str[i] == ')') { count--; }