Created
November 29, 2018 19:46
-
-
Save kalachevmax/19c4887786472ff7192033a177c9091e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Строка состоит из произвольной последовательности символов, перемежаемых открывающей "(" и закрывающей ")" скобочками. Необходимо проверить, что каждой открывающей скобочке соответствует закрывающая. | |
// Вход: строка | |
// Выход: "ok" или "error: $i", где $i - индекс ошибочного символа. | |
// Учитывается последний некорректный символ. | |
String parse(String str) { | |
return null; | |
} | |
bool hasErrors = false; | |
List<String> messages = []; | |
void main() { | |
test('1', () { | |
expect(parse('(a((a)ab()))'), equals('ok')); | |
}); | |
test('2', () { | |
expect(parse(')ab)'), equals('error: 0')); | |
}); | |
test('3', () { | |
expect(parse('()(ab))'), equals('error: 6')); | |
}); | |
test('4', () { | |
expect(parse('()(ab)(gh'), equals('error: 6')); | |
}); | |
test('5', () { | |
expect(parse('()((ab)(gh'), equals('error: 7')); | |
}); | |
if(!hasErrors ){ | |
print('💪Tests are passed! \n\n'); | |
} else { | |
print('💩 Tests aren\'t passed! \n\n'); | |
} | |
print(messages.join('\n')); | |
} | |
typedef bool Checker(dynamic input); | |
Checker equals(dynamic input) { | |
return (dynamic internalInput) { | |
input.toString() == internalInput.toString() | |
? true | |
: throw AssertionError('value: $input is not equal: $internalInput'); | |
}; | |
} | |
void test(String name, Function input) { | |
try { | |
input(); | |
messages.add('✓ $name'); | |
} catch (e) { | |
hasErrors = true; | |
if (e is AssertionError) { | |
messages.add('✗ $test failed \n name: $name\n exception: ${e.message}'); | |
} | |
} | |
} | |
void expect(dynamic input, bool validator(dynamic validatorInput)) { | |
validator(input); | |
} | |
class Solver { | |
final String _str; | |
Solver(this._str); | |
String _parse(String str) { | |
final List<String> stack = []; | |
int lastIndex; | |
for (var i = 0; i < _str.length; i++) { | |
if (str[i] == '(') { | |
stack.add(str[i]); | |
lastIndex = i; | |
} else if (str[i] == ')') { | |
if (stack.isNotEmpty && stack.last == '(') { | |
stack.removeLast(); | |
} else { | |
return 'error: $i'; | |
} | |
} | |
} | |
return stack.isEmpty ? 'ok' : 'error: $lastIndex'; | |
} | |
String solve() => _parse(_str); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment