思路
- 从最里面的括号开始反转
- 如果从最里面开始反转的话,就是后进先出,用栈,先匹配到最里面的括号
- 非常重要的一点,
栈中保存的是'('的位置
- 对’(‘和’)'之间的字符串进行反转
- 写main函数的时候干了蠢事,用了const字符串,结果交换函数用不了,搞了半天没看出来
代码
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<stdlib.h>
void reverse(char *s,int start,int end){
int start_i=start;
int end_i=end;
char temp;
while (start_i<end_i)
{
temp = s[start_i];
s[start_i]=s[end_i];
s[end_i]=temp;
start_i++;
end_i--;
}
}
char* reverseParentheses(char * s){
int len = strlen(s);
int i=0,tl=0,count=0,j=0;
for(i=0;i<len;i++){
if(isalpha(s[i])){
tl++;
}
else count++;
}
char *re =(char*)malloc((tl+1)*sizeof(char));
i=0;j=len-1;
int stack[len],top=-1;
memset(stack,0,len*sizeof(int));
for(i=0;i<len;i++){
if(s[i]=='('){
stack[++top]=i;
}
else if(s[i]==')'){
reverse(s,stack[top--]+1,i-1);
}
}
for(i=0;i<len;i++)
printf("%c",s[i]);
printf("\n");
i=0;
j=0;
while (i<len)
{
if(isalpha(s[i]))
re[j++]=s[i++];
else
i++;
}
re[j]='\0';
return re;
}
int main(){
char s[] = "sxmdll(q)eki(x)";
char* re = reverseParentheses(s);
printf("re = %s\n",re);
}