-
Notifications
You must be signed in to change notification settings - Fork 0
/
394.字符串解码.c
113 lines (100 loc) · 2.02 KB
/
394.字符串解码.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/*
* @lc app=leetcode.cn id=394 lang=c
*
* [394] 字符串解码
*/
// @lc code=start
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#define MAX_VAL 50000
char charStack[MAX_VAL];
int numStack[MAX_VAL];
int top = -1;
int numtop = -1;
void PushChar(char ch){
if(top == MAX_VAL-1){
printf("Stack Overflow\n");
return;
}
charStack[++top] = ch;
}
char PopChar(){
if(top == -1){
printf("Stack Empty");
return '0';
}
return charStack[top--];
}
char PeekChar(){
if(top == -1){
printf("Stack Empty");
return '0';
}
return charStack[top];
}
void PushInt(int val){
if(numtop == MAX_VAL-1){
printf("Num Stack overflow\n");
return;
}
numStack[++numtop] = val;
}
int PopInt(){
if(numtop == -1){
printf("Num Stack Empty\n");
return 0;
}
return numStack[numtop--];
}
int PeekInt(){
if(numtop == -1){
printf("Num Stack Empty\n");
return 0;
}
return numStack[numtop];
}
void Multiply(){
int times = PopInt();
int k = top;
while(charStack[k] != '[') k--;
int poplen = top - k;
k = 0;
char pops[poplen];
while(PeekChar() != '['){
pops[k++] = PopChar();
}
PopChar();
for(int i=0; i<times; i++){
for(int j=k-1; j>=0; j--){
PushChar(pops[j]);
}
}
}
char * decodeString(char * str){
int len = strlen(str);
int num = 0;
for(int j=0; j<len; j++){
if(str[j] >= '0' && str[j] <= '9'){
num = num*10 + (str[j]-'0');
} else {
if(str[j] == '['){
PushInt(num);
num = 0;
}
if(str[j] != ']'){
PushChar(str[j]);
} else {
Multiply();
}
}
}
int length = top+1;
char *res = (char *)malloc(sizeof(char)*(length+1));
res[length] = '\0';
for(int j=length-1; j>=0; j--){
res[j] = PopChar();
}
return res;
}
// @lc code=end