LeetCode题解——ZigZag Conversion
2024-09-09 20:39:21
题目:
把一个字符串按照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;
}
};
最新文章
- css的padding
- cdoj 树上战争(Battle on the tree) Label:并查集?
- cocos2dx 3.0 之 lua 创建类 (二)
- 安装max plugin wizard
- Php中正则小结(一)
- [TypeScript] Avoid any type
- create OpenVPN on ubuntu12.04
- 【转】Java 并发:Executors 和线程池
- MySQL索引的使用方式
- Sourcetree的安装与使用
- js判定是否为chrome,区分搜狗+360
- net Core TOptions和热更新
- css新增伪类
- Java中资料的上传与下载
- 转载 - CNN感受野(receptive-fields)RF
- 【没有注意过的细节】用scanf读一个unsigned char? %hhu 的用法
- Java的Integer和int有什么区别
- 20145220韩旭飞《网络对抗》Exp2 后门原理与实践
- ASP.NET错误处理的方式(一)
- bae3.0第二步 添加一个空的django项目
热门文章
- 为什么dubbo使用ZkClient作为zookeeper的客户端
- IE 坑爹的浏览器兼容模式
- Delphi XE5 android openurl(转)
- 1037: [ZJOI2008]生日聚会Party - BZOJ
- .substr()在字符串每个字母前面加上一个1
- Scroll文字滚动js
- leetcode2	 Two Sum II – Input array is sorted
- cf 357C
- 1028-Digital Roots
- [codility]Min-abs-sum