【发布时间】:2011-08-29 22:02:37
【问题描述】:
考虑以下对字符串的转换。给定多个行和一个字符串作为输入,将该字符串以之字形在行间来回写入。例如,给定输入
请将我转换为自定义的锯齿形打印格式
三行,我们将字符串写成这样的之字形:
P s n t o s i z a i n r
l a e o v r m t a u t m z d i z g r n i g o m t
e c e e c o e g p t f a
(请不要编辑这个打印输出,这是必需的输出,它不是真正的之字形,它是 一个定制的之字形)
最后,我们将每一行的比赛连接在一起得到结果字符串
Psntosizainrlaeovrmtautmzdizgrnigomteceecoegptfa
我有一个解决这个问题的算法草图,我在这里用伪代码写了出来:
it is asking about the relationship between {index} and {output row and col}
Def:
down = false;
up = false;
r=0;
c=0;
char[][] output;
there are three cases here:
case 1:
index % 4 == 0, it is the beginning of a down printing
r = 0;
output[r][c] = in.charAt(index);
c++;
down = true; up = false;
case 2:
index%4 != 0 && down = true;
r = index % 4;
output[r][c] = in.charAt(index);
if( r == 2){ up = true; down = false; c++;} // when come to the last row of a down formatting
case 3:
index%4 != 0 && up == true;
r = 4- index%4;
output[r][c] = in.charAt(index);
c++;
对于一般的解决方案,我可以将 4 替换为 nRows+1;
虽然我认为这可行,但我对此不太满意。有没有人有更清晰或更快的算法来解决这个问题?
【问题讨论】:
-
这是作业吗?如果是这样,请标记为这样。此外,此代码不是 java - 请适当编辑您的标签
-
@Bohemian:可能是伪代码
标签: java string algorithm implementation