Skip to content

Instantly share code, notes, and snippets.

@eyasuyuki
Last active January 6, 2024 23:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eyasuyuki/f3d829f470d0003c4a6baf7fdd94dc1d to your computer and use it in GitHub Desktop.
Save eyasuyuki/f3d829f470d0003c4a6baf7fdd94dc1d to your computer and use it in GitHub Desktop.
kakko-kokka.dart
void main() {
testExtractStrings();
}
List<String> extractStrings(String input) {
List<String> result = [];
List<int> stack = [];
int startIndex = 0;
for (int i = 0; i < input.length; i++) {
if (input[i] == '[') {
if (stack.isEmpty) {
String head = input.substring(startIndex, i);
result.add(head);
}
if (stack.isEmpty) {
startIndex = i + 1;
}
stack.add(i);
} else if (input[i] == ']' && stack.isNotEmpty) {
if (stack.length == 1) {
String extractedString = input.substring(startIndex, i);
startIndex = i + 1;
result.add(extractedString);
}
stack.removeLast();
}
}
if (startIndex != 0) {
result.add(input.substring(startIndex));
}
return result;
}
void testExtractStrings() {
String input = "あいうえおかきく[け[こ]さ]し]す]せそ";
List<String> expected = ["あいうえおかきく", "け[こ]さ", "し]す]せそ"];
List<String> result = extractStrings(input);
result.forEach((String line) {
print(line);
});
if (result.length != expected.length) {
print("Test failed: Length mismatch");
print("Expected length: ${expected.length}, Actual length: ${result.length}");
return;
}
for (int i = 0; i < result.length; i++) {
if (result[i] != expected[i]) {
print("Test failed: Mismatch at index $i");
print("Expected: ${expected[i]}, Actual: ${result[i]}");
return;
}
}
print("Test passed!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment