Leetcode 3206. Alternating Groups I
Given a string s
, return an array representing the length of each consecutive group of characters that alternate between letters and digits. For example, for the string “a1b2c3”, the groups are “a”, “1”, “b”, “2”, “c”, “3”, so the result should be [1, 1, 1, 1, 1, 1]
.
s
? Input: "a1b2c3"
Output: [1, 1, 1, 1, 1, 1]
Input: "abc123"
Output: [3, 3]
Input: "a12b3c4"
Output: [1, 2, 1, 1, 1]
Here’s the C++ implementation:
#include <iostream>
#include <vector>
#include <string>
std::vector<int> alternatingGroups(const std::string& s) {
std::vector<int> result;
if (s.empty()) return result;
// Initialize the first group length
int groupLength = 1;
// Identify if the first character is a digit or a letter
bool isCurrentDigit = isdigit(s[0]);
for (size_t i = 1; i < s.size(); ++i) {
// Check if the character type has changed
if ((isCurrentDigit && isalpha(s[i])) || (!isCurrentDigit && isdigit(s[i]))) {
// Add the current group length to the result
result.push_back(groupLength);
// Reset the group length
groupLength = 1;
// Update the current type flag
isCurrentDigit = !isCurrentDigit;
} else {
// Increment the current group length
groupLength++;
}
}
// Add the last group length to the result
result.push_back(groupLength);
return result;
}
int main() {
std::string input = "a12b3c4";
std::vector<int> output = alternatingGroups(input);
// Print the result
for (int length : output) {
std::cout << length << " ";
}
return 0;
}
s
.This code correctly handles the grouping and tracking of alternating letters and digits.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?