C ++,199个 183 181 175字节
此模板函数接受行作为字符串的集合(可能是宽字符串),并以一对迭代器的形式传递。
#include<algorithm>//
template<class I>bool
f(I a,I b){return!~+(
*a+b[-1]).find(' ')&&
std::all_of(a,b,[&a](
auto&s){return' '+-s.
back()&&s[0]-' '&&a->
size()==s.size();});}
感谢用户Erroneous提醒我该back()
成员std::string
并指出npos+1
为零。
非高尔夫等效
唯一真正的打高尔夫球是将第一行和最后一行连接起来,这样我们就可以find
对其中的空间进行单个操作。
#include <algorithm>
template<class It>
bool f(It a, It b)
{
return (*a+b[-1]).find(' ') == a->npos
&& std::all_of(a, b,
[=](auto s) {
return s.back() != ' '
&& s.front() != ' '
&& s.size() == a->size(); });
}
测试程序
#include <iostream>
#include <string>
#include <vector>
int expect(const std::vector<std::string>& v, bool expected)
{
bool actual = f(v.begin(), v.end());
if (actual == expected) return 0;
std::cerr << "FAILED " << (expected ? "truthy" : "falsey") << " test\n";
for (auto const& e: v)
std::cerr << " |" << e << "|\n";
return 1;
}
int expect_true(const std::vector<std::string>& v) { return expect(v, true); }
int expect_false(const std::vector<std::string>& v) { return expect(v, false); }
int main()
{
return
// tests from the question
+ expect_true({"sdghajksfg"})
+ expect_true({"asdf", "jkl;",})
+ expect_true({"qwerty", "u i op", "zxcvbn",})
+ expect_true({"1234", "5 6", "7890",})
+ expect_true({"abcd", "e fg", "hijk",})
+ expect_false({"a b c",})
+ expect_false({"123", "456", "7 9",})
+ expect_false({"12", "345",})
+ expect_false({"qwerty", " uiop", "zxcvnm",})
+ expect_false({"1234", "567", "8900",})
// extra tests for leading and trailing space
+ expect_false({"123", " 56", "789"})
+ expect_false({"123", "45 ", "789"})
// the function source
+ expect_true({"#include<algorithm>//",
"template<class I>bool",
"f(I a,I b){return!~+(",
"*a+b[-1]).find(' ')&&",
"std::all_of(a,b,[&a](",
"auto&s){return' '+-s.",
"back()&&s[0]-' '&&a->",
"size()==s.size();});}",})
;
}