这是一道面试题 寻找从字符串中修剪多个空格的最佳解决方案。这个操作应该是就地操作。
input = "I Like StackOverflow a lot"
output = "I Like StackOverflow a lot"
不允许使用字符串函数,因为这是一道面试题。寻找问题的算法解决方案。
最佳答案
是否使用 <algorithm>
是否符合“算法解决方案”?
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
struct BothAre
{
char c;
BothAre(char r) : c(r) {}
bool operator()(char l, char r) const
{
return r == c && l == c;
}
};
int main()
{
std::string str = "I Like StackOverflow a lot";
std::string::iterator i = unique(str.begin(), str.end(), BothAre(' '));
std::copy(str.begin(), i, std::ostream_iterator<char>(std::cout, ""));
std::cout << '\n';
}
关于c++ - 面试题: Trim multiple consecutive spaces from a string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5561138/