As the compiler tries to tell you, the issue is that the types of start + k -1
and s.size() - 1
are different. So one way to fix this is to change the types of start
and k
to std::size_t
:
std::string reverseStr(std::string s, std::size_t k) {
for (std::size_t start = 0; start < s.size(); start += 2 * k) {
std::size_t end = std::min(start + k - 1, s.size() - 1);
while (start < end) {
swap(s[start], s[end]);
start++;
end--;
}
}
return s;
}
Alternatively you can just cast s.size() - 1
to int
:
int end = std::min(start + k - 1, static_cast<int>(s.size() - 1));
There is also the third way to explicitly specify the template parameter of std::min
, but that might trigger signed-to-unsigned / unsigned-to-signed conversion warnings of your compiler:
int end = std::min<int>(start + k - 1, s.size() - 1);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…