题目描述: For a string xx, Bobo defines x ∞=xxx…,which is xx repeats for infinite times, resulting in a string of infinite length. Bobo has two strings aa and bb. Find out the result comparing a ∞ and b ∞ in lexicographical order.You can refer the wiki page for further information of Lexicographical Order. 输入描述: The input consists of several test cases terminated by end-of-file. The first line of each test case contains a string a, and the second line contains a string b. 1 ≤∣a∣,∣b∣≤ 10 5 a, b consists of lower case letters. The total length of input strings does not exceed 2 X 10 6 输出描述: For each test case, print “
=
” (without quotes) if a ∞ =b ∞ . Otherwise, print “
<
” if a ∞
< b∞ , or “
>
” if a ∞ > b ∞ . 示例: 输入:
aa
b
zzz
zz
aba
abaa
输出:
<
=
>
代码:
#include
using namespace std;
int main()
{
string s1, s2;
int n1, n2;
while (cin >> s1 >> s2)
{
n1 = s1.length();
n2 = s2.length();
int t = max(n1, n2);
bool f = false;
for (int i = 0; i < t * 2; i++)
{
if (s1[i % n1] > s2[i % n2]) //核心代码
{
cout << ">" << endl;
f = true;
break;
}
else if (s1[i % n1] < s2[i % n2])
{
cout << "<" << endl;
f = true;
break;
}
}
if (!f)
{
printf("=\n");
}
}
}
这道题的核心就在于s1[i % n1] 与 s2[i % n2]的比较上。
i % n的实现类似于约瑟夫环,使得此题不需要对字符串进行额外的操作就能进行比较。
由题意知无限个s1与s2拼接进行比较,如果利用最小公倍数将s1与s2的字符数拼接到相同时再比较并没有什么错误,但是问题在于这道题的数据较大,会TLE。
因此通过i % n这种实现,使得不需要对字符串进行拼接等额外操作就能比较同位置两字符串的字符大小。
