#include <iostream>
using namespace std;
int main()
{
string s, s1, s2;
char c;
while (cin >> c, c != ',') s += c;
while (cin >> c, c != ',') s1 += c;
while (cin >> c) s2 += c;
if (s.size() < s1.size() || s.size() < s2.size()) puts ("-1");
else
{
int l = 0;
while (l + s1.size() <= s.size())
{
int k = 0;
while (k < s1.size())
{
if (s[l + k] != s1[k]) break;
k ++ ;
}
if (k == s1.size()) break;
l ++ ;
}
int j = s.size() - s2.size();
while (j >= 0)
{
int k = 0;
while (k < s2.size())
{
if (s[j + k] != s2[k]) break;
k ++ ;
}
if (k == s2.size()) break;
j -- ;
}
l += s1.size() - 1;
if (j <= l) puts("-1");
else printf("%d\n", j - l - 1);
}
return 0;
}
for循环写法
#include <iostream>
using namespace std;
int main()
{
string s, s1, s2;
char c;
while (cin >> c, c != ',') s += c;
while (cin >> c, c != ',') s1 += c;
while (cin >> c) s2 += c;
if (s.size() < s1.size() || s.size() < s2.size()) puts("-1");
else
{
int l = 0;
for (; l + s1.size() < s.size(); l ++ )
{
int k = 0;
for (; k < s1.size(); k ++ )
if (s[l + k] != s1[k]) break;
if (k == s1.size()) break;
}
int j = s.size() - s2.size();
for (; j >= 0; j --)
{
int k = 0;
for (; k < s2.size(); k ++ )
if (s[j + k] != s2[k]) break;
if (k == s2.size()) break;
}
l += s1.size() - 1;
if (j < l) puts("-1");
else printf("%d\n", j - l - 1);
}
return 0;
}
简洁写法(看起来干净些)
#include <iostream>
using namespace std;
int main()
{
string a, b, c;
char d;
while (cin >> d, d != ',') a += d;
while (cin >> d, d != ',') b += d;
while (cin >> d) c += d;
if (b.size() > a.size() || c.size() > a.size()) puts("-1");
else
{
int i = 0;
for (; i + b.size() < a.size(); i ++ )
{
int j = 0;
while (j < b.size() && a[i + j] == b[j]) j ++ ;
if (j == b.size()) break;
}
int k = a.size() - c.size();
for (; k > 0; k -- )
{
int n = 0;
while (n < c.size() && a[k + n] == c[n]) n ++ ;
if (n == c.size()) break;
}
i += b.size() - 1;
if (k < i) puts("-1");
else cout << k - i - 1 << endl;
}
return 0;
}