题目

把一个字符串按照Z型排列后打印出来,例如 "PAYPALISHIRING" 重新排列后为3行,即

P   A   H   N
A P L S I I G
Y I R

那么输出为"PAHNAPLSIIGYIR"

解法

细节实现题,假如重新排列为5行,那么排列后的下标分布应该为

0          8            16        24

1      7  9         15    17      23 

2    6    10    14    18    22

3  5      11  13      19  21

4          12          20

可以看出规律,输出为5行的时候,每两个完整列之间的下标差为8 = (2 × 5 - 2);

然后是从第二行到倒数第二行,每两个完整列之间都插入了一个下标,插入的下标与左边列之间的差依次递减2。

代码

 class Solution {
public:
string convert(string s, int nRows) {
if(s.size() <= || nRows <= )
return s; string result;
for(int i = ; i < nRows; ++i)
for(int j = , idx = i; idx < s.size(); ++j, idx = (*nRows - ) * j + i) //idx为计算出来的原串下标
{
result.append(, s[idx]); if(i == || i == nRows - ) //第一行和最后一行的完整列中间没有插入字符
continue; if(idx + *(nRows - i - ) < s.size()) //计算插入的字符,其下标与左边的差
result.append(, s[idx + *(nRows - i - )]);
} return result;
}
};

最新文章

  1. css的padding
  2. cdoj 树上战争(Battle on the tree) Label:并查集?
  3. cocos2dx 3.0 之 lua 创建类 (二)
  4. 安装max plugin wizard
  5. Php中正则小结(一)
  6. [TypeScript] Avoid any type
  7. create OpenVPN on ubuntu12.04
  8. 【转】Java 并发:Executors 和线程池
  9. MySQL索引的使用方式
  10. Sourcetree的安装与使用
  11. js判定是否为chrome,区分搜狗+360
  12. net Core TOptions和热更新
  13. css新增伪类
  14. Java中资料的上传与下载
  15. 转载 - CNN感受野(receptive-fields)RF
  16. 【没有注意过的细节】用scanf读一个unsigned char? %hhu 的用法
  17. Java的Integer和int有什么区别
  18. 20145220韩旭飞《网络对抗》Exp2 后门原理与实践
  19. ASP.NET错误处理的方式(一)
  20. bae3.0第二步 添加一个空的django项目

热门文章

  1. 为什么dubbo使用ZkClient作为zookeeper的客户端
  2. IE 坑爹的浏览器兼容模式
  3. Delphi XE5 android openurl(转)
  4. 1037: [ZJOI2008]生日聚会Party - BZOJ
  5. .substr()在字符串每个字母前面加上一个1
  6. Scroll文字滚动js
  7. leetcode2 Two Sum II – Input array is sorted
  8. cf 357C
  9. 1028-Digital Roots
  10. [codility]Min-abs-sum