March 8, 2022
Here is the link.
C# | learn from failed test cases
March 6, 2022
Introduction
It is an easy algorithm, but it is so challenge since I failed so many test cases, so I continuously modified the logic in order to pass all test cases. I have two weeks to practice Leetcode in order to prepare Meta phone screen, I just choose to solve as many algorithms as I can and warmup my coding skills.
Learn from failed test cases | Write down and review later
test case 166/322
Input:
"internationalization"
"i5a11o1"
Output:
false
Expected:
true
Fix: Do not mix c with 'c', c is in the range from 0 to 9. '9' - c >= 0
11 / 322 test cases passed.
Input:
"a"
"01"
Output:
true
Expected:
false
Fix: Add edge case to check number should not start from 0 digit.
12 / 322 test cases passed.
Runtime Error Message:
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
Last executed input:
"hi"
"2i"
Fix: Add index-out-of-range check for word array, wIndex - check in the range
314 / 322 test cases passed.
Input:
"hi"
"1"
Output:
true
Expected:
false
Fix: make sure that return statement should check that search in word is completed
return wIndex == length;
The following C# code passes online judge.
public class Solution {
public bool ValidWordAbbreviation(string word, string abbr) {
if (word == null || word.Length == 0 || abbr == null || abbr.Length == 0)
return false;
var length = word.Length;
var aLength = abbr.Length;
var wIndex = 0;
var index = 0;
var digits = 0;
while (index < aLength)
{
var c = abbr[index];
if ((c - '0') >= 0 && ('9' - c) >= 0)
{
var digit = c - '0';
// test case: "a", "01"
if(digit == 0 && (index == 0 || abbr[index - 1] >='a') && (index + 1 < aLength && (abbr[index + 1] - '0' >=0)))
{
return false;
}
digits = digits * 10 + (c - '0');
if (index == aLength - 1 || abbr[index + 1] >= 'a')
{
if (wIndex + digits > length)
return false;
wIndex += digits;
}
}
else
{
digits = 0;
if (wIndex >= length || word[wIndex++] != abbr[index])
{
return false;
}
}
index++;
}
return wIndex == length;
}
}
No comments:
Post a Comment