leetcode ZigZag Conversion
2014-03-16 18:27
363 查看
ZigZag Conversion
Total Accepted: 5160 TotalSubmissions: 22837My Submissions
The string
"PAYPALISHIRING"is
written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N A P L S I I G Y I R
And then read line by line:
"PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3)should return
"PAHNAPLSIIGYIR".
Have you been asked this question in an interview?
I treat this problem in a direct way:
class Solution { public: string convert(string s, int nRows) { int i, j, flg; vector<char> vec; vector<vector<char>> zigzag(nRows,vec); for (i = 0, j = 0, flg = 1; i < s.length(); ++i) { zigzag[j].push_back(s[i]); if (flg && j == nRows - 1) flg = 0; else if (!flg && j == 0) flg = 1; if (nRows > 1) j = flg > 0 ? (j + 1):(j - 1); } string res = ""; for (i = 0; i < nRows; ++i) for (j = 0; j < zigzag[i].size(); ++j) res += zigzag[i][j]; return res; } };
But a better way is from http://blog.unieagle.net/2012/11/08/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Azigzag-conversion/
class Solution { public: string convert(string s, int nRows) { int len = s.length(), zigSize = nRows*2 - 2, i, j, tmp; string res = ""; if (nRows <= 1) return s; for (i = 0; i < nRows; ++i) { for (j = i; j < len; j += zigSize) { res += s.substr(j,1); tmp = j + zigSize - 2 * i; if (i != 0 && i != nRows - 1 && tmp < len) { res += s.substr(tmp, 1); } } } return res; } };
相关文章推荐
- leetcode ZigZag Conversion
- Leetcode ZigZag Conversion
- LeetCode [Day 6] ZigZag Conversion 题解
- Leetcode: zigzag-conversion
- Leetcode ZigZag Conversion
- [Leetcode]ZigZag Conversion 笨方法
- leetcode之ZigZag Conversion
- [LeetCode 解题报告]006.ZigZag Conversion
- [编程练习]ZigZag Conversion <LeetCode-6>
- 6.[leetcode] ZigZag Conversion
- leetcode 6 ZigZag Conversion(水题)
- leetcode problem 6 ZigZag Conversion
- leetcode6 ZigZag Conversion
- Leetcode ZigZag Conversion
- [LeetCode] ZigZag Conversion [9]
- LeetCode--zigzag-conversion
- LeetCode 006 ZigZag Conversion
- [LeetCode-Algorithms-6] "ZigZag Conversion" (2017.9.28-WEEK4)
- 【LeetCode】6.ZigZag Conversion N型排列问题
- Leetcode 6 ZigZag Conversion