这是一个面试问题寻找最佳的最佳解决方案来修剪字符串中的多个空格.此操作应该是就地操作.
input = "I Like StackOverflow a lot"
output = "I Like StackOverflow a lot"
Run Code Online (Sandbox Code Playgroud)
不允许使用字符串函数,因为这是一个面试问题.寻找问题的算法解决方案.
Cub*_*bbi 14
使用是否<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';
}
Run Code Online (Sandbox Code Playgroud)
测试运行:https://ideone.com/ITqxB
dec*_*ype 11
一个c ++ 0x - 使用lambda而不是常规函数对象的解决方案.与Cubbi的解决方案相比.
#include <string>
#include <algorithm>
int main()
{
std::string str = "I Like StackOverflow a lot";
str.erase(std::unique(str.begin(), str.end(),
[](char a, char b) { return a == ' ' && b == ' '; } ), str.end() );
}
Run Code Online (Sandbox Code Playgroud)
Meh*_*dad 10
保留两个索引:下一个可用的字母(例如i
),以及您正在检查的当前索引(例如j
).
只需循环遍历所有字符j
,每当看到一个字母时,将其复制到索引i
,然后递增i
.如果您看到空格前面没有空格,也请复制空格.
我认为这可以就地工作......
我只想这样做:
int main(int argc, char* argv[])
{
char *f, *b, arr[] = " This is a test. ";
f = b = arr;
if (f) do
{
while(*f == ' ' && *(f+1) == ' ') f++;
} while (*b++ = *f++);
printf("%s", arr);
return 0;
}
Run Code Online (Sandbox Code Playgroud)