++-+--+ -++--++
4
解析:这道题NYOJ上的数据比较水,而且题目说+号和它相邻的减号交换,并没有说—号可以与它相邻的加号交换,但是OJ上默认都可以交换的
#include <iostream> #include <string> using std::endl; using std::cout; using std::cin; using std::string; int main() { string str1,str2; while(cin >> str1 >>str2) { int len; //首先判断字符串的长度和字符串中+号的数量是否一致 if(str1.length()!=str2.length()) { cout << -1 <<endl; continue; }else{ len = str1.length(); } int len1=0,len2=0; for(int i=0; i<len; ++i) { if(str1[i]==‘+‘) len1++; if(str2[i]==‘+‘) len2++; } if(len1!=len2) continue; int cnt=0; //然后进行移动匹配 for(int i=0; i<len; ++i) { if(str1[i] != str2[i]) { for(int j=i+1;j<len;++j) { if(str1[j] == str2[i]) { cnt = cnt +(j-i); //此处可以进行交换,但是对于该题来说没必要进行交换 //swap(str1[j] , str1[i]); str1[j] = str1[i]; break; } } } } cout << cnt <<endl; } return 0; }
原文:http://blog.csdn.net/computer_liuyun/article/details/22272355