/*
++-+--+
-++--++
每个子符串长度不超过5000。不存在,输出-1
4*/
#include<stdio.h>
#include<string.h>
#include<stack>
#include<algorithm>
using namespace std;
stack<int> S1,S2;
int Abs(int x){
return x>=0?x:-x;
}
int main(){
char str1[5001],str2[5001];
while(~scanf("%s",str1)){
scanf("%s",str2);
if(strlen(str1)!=strlen(str2)){
printf("-1\n");
continue;
}
while(!S1.empty()) S1.pop();
while(!S2.empty()) S2.pop();
for(int i=0;str1[i];++i){
if(str1[i]=='-')//先将该字符串的所有减号 入栈
S1.push(i);
}
for(int i=0;str2[i];++i){
if(str2[i]=='-')
S2.push(i);
}
if(S1.size()!=S2.size()){//如果两个字符栈的个数不一样
printf("-1\n");//打印-1
continue;//继续进行下一轮测试
}
int ans=0;
while(!S1.empty()){//当栈不空的时候
int i=S1.top();//获取栈顶元素对应减号的下标
int j=S2.top();
ans += Abs(i-j);//累加统计移动次数
S1.pop();//并且栈顶元素出栈 ,计算下一对减号
S2.pop();
}
printf("%d\n",ans);
}
return 0;
}
+-字符串
最新推荐文章于 2022-02-26 14:36:14 发布