LeetCode第6题--Z 字形变换
2019-03-26 22:22
363 查看
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 “LEETCODEISHIRING” 行数为 3 时,排列如下:
L C I R
E T O E S I I G
E D H N
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“LCIRETOESIIGEDHN”。
string convert(string s, int numRows) { /*从左至右迭代字符串*/ /*if(numRows == 1) return s; vector<string> vecRows(min(numRows, int(s.length()))); int curRow = 0; bool goingDown = false; //判断方向标志位 string strRes = ""; for(char ch : s) { vecRows[curRow] += ch; if(curRow == 0 || curRow == numRows-1) goingDown = !goingDown; curRow = goingDown ? curRow+1 : curRow-1; } for(string str : vecRows) { strRes += str; } return strRes;*/ /*按行读取*/ if(numRows == 1) return s; string strRes = ""; int len = s.length(); int cycle = 2 * numRows - 2; //循环周期为2倍行数减去首尾 for(int i = 0; i < numRows; i++) { for(int j = 0; j + i < len; j += cycle) //每次递进一个周期 { strRes += s[i+j]; //首尾及中间各行开头索引 if(i != 0 && i != numRows-1 && j+cycle-i < len) { strRes += s[j+cycle-i]; //中间各行中间的索引,cycle-1为该周期内对应字符的索引,j为其前面的周期数 } } } return strRes; }
相关文章推荐
- leetCode第6题,Z字形变换
- Leetcode(C++)——6. Z 字形变换
- 【leetcode】Zigzag Z 字形变换
- 【Leetcode】6.Z字形变换
- 【LeetCode】之字形变换
- LeetCode题解(python)-6. Z 字形变换
- LeetCode 6 Z字形变换(字符串)
- LeetCode | 6. ZigZag Conversion(之字形变换)
- LeetCode6. Z 字形变换
- 基础算法之Z字形变换(Leetcode-6)
- Z 字形变换(LeetCode)
- LeetCode6.python实现:Z 字形变换问题☆☆
- leetcode 6. Z 字形变换(Java版)
- Z字形变换 - LeetCode
- leetcode Z 字形变换
- [LeetCode] Zigzag Iterator 之字形迭代器
- Leetcode 第6题 ZIGZAG后,行列输出
- LeetCode Word Ladder 找单词变换梯
- [LeetCode-6]ZigZag字符串的变换输出
- Leetcode 127. Word Ladder 字符变换 解题报告