medium
1 views
Expand Alphabets
Given a string containing alternating alphabets and their counts, expand each alphabet by repeating it according to its count.
Understand the Problem
Problem Statement
Problem: Given a string S with alphabets and their count, repeat the alphabets based on their count and print the value as the output.
Constraints
- 1 ≤ Length of S ≤ 100
- Input string contains only lowercase alphabets followed by their counts (digits)
- Each alphabet is followed by exactly one or more digits representing its count
- Alphabets and counts alternate in the input string
- Count values are positive integers
Examples
Example 1
Input
a2c5z4Output
aaccccczzzzExplanation
a appears 2 times, c appears 5 times, z appears 4 times. So the output is 'aa' + 'ccccc' + 'zzzz' = 'aaccccczzzz'.
Example 2
Input
x3y1z2Output
xxxyzExplanation
x appears 3 times, y appears 1 time, z appears 2 times. So the output is 'xxx' + 'y' + 'zz' = 'xxxyz'.
Example 3
Input
p10Output
ppppppppppExplanation
p appears 10 times. So the output is 'p' repeated 10 times = 'pppppppppp'.
Solution
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char s[101];
fgets(s, sizeof(s), stdin);
int len = strlen(s);
if (s[len-1] == '\n') {
s[len-1] = '\0';
len--;
}
char current_char = '\0';
int count = 0;
for (int i = 0; i < len; i++) {
if (isalpha(s[i])) {
// If we have a previous character with count, print it
if (current_char != '\0' && count > 0) {
for (int j = 0; j < count; j++) {
printf("%c", current_char);
}
}
// Set new character
current_char = s[i];
count = 0;
} else if (isdigit(s[i])) {
// Build the count
count = count * 10 + (s[i] - '0');
}
}
// Print the last character with its count
if (current_char != '\0' && count > 0) {
for (int j = 0; j < count; j++) {
printf("%c", current_char);
}
}
printf("\n");
return 0;
}Time:O(n)
Space:O(1)
Approach:
C Solution Explanation:
- Read input string using fgets()
- Remove newline character if present
- Use a state machine approach with variables current_char and count
- Iterate through each character:
- If it's an alphabet: print previous character (if any) with its count, then set current_char to this new character
- If it's a digit: build the count by multiplying by 10 and adding current digit
- After loop, print the last character with its count
- Time complexity: O(n) where n is string length
- Space complexity: O(1) excluding input storage
Visual Explanation
Loading diagram...