描述
You need to write a function grid that returns an alphabetical grid of size NxN, where a = 0, b = 1, c = 2…
Examples:
grid(4)
a b c d
b c d e
c d e f
d e f g
grid(10)
a b c d e f g h i j
b c d e f g h i j k
c d e f g h i j k l
d e f g h i j k l m
e f g h i j k l m n
f g h i j k l m n o
g h i j k l m n o p
h i j k l m n o p q
i j k l m n o p q r
j k l m n o p q r s
After “z” comes “a”
If function receive N < 0 should return:“”
解决方案
1
#include <string>
std::string grid(int n) {
std::string s = "abcdefghijklmnopqrstuvwxyz";
std::string ans;
if(n < 0)
return "";
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
ans += s[(i + j) % 26];
ans += j == n - 1 ? "" : " ";
}
ans += i == n - 1 ? "" : "\n";
}
return ans;
}
使用append(char)的方式会不通过。 可能取地址后出现问题,有人测试过+= 比append 高效,在C#中+=会产生GC 也许C++机制不同
2
#include <string>
std::string grid(int n){
if(n==0)return "";
char c='a';
int no=0,ano=0;
std::string sum;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
sum+=c+no;
if(j!=n-1)sum+=' ';
if(no+1!=26)no++;
else no=0;
}
if(ano+1!=26)ano++;
else ano=0;
no=ano;
if(i!=n-1)sum+="\n";
}
return sum;
}
+= char 也好使