[LeetCode] ZigZag Conversion 解题报告
2013-01-15 11:29
525 查看
The string
Write the code that will take a string and make this conversion given a number of rows:
» Solve this problem
[解题思路]
数学题。巨无聊的一道题,真正面试过程中,不大可能出这种问题。
n=4
P I N
A L S I G
Y A H R
P I
N=5
P H
A S I
Y I R
P L I G
A N
所以,对于每一层主元素(红色元素)的坐标 (i,j)= (j+1 )*n +i
对于每两个主元素之间的插入元素(绿色元素),(j+1)*n -i
"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 RAnd 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".
» Solve this problem
[解题思路]
数学题。巨无聊的一道题,真正面试过程中,不大可能出这种问题。
n=4
P I N
A L S I G
Y A H R
P I
N=5
P H
A S I
Y I R
P L I G
A N
所以,对于每一层主元素(红色元素)的坐标 (i,j)= (j+1 )*n +i
对于每两个主元素之间的插入元素(绿色元素),(j+1)*n -i
[code]1: string convert(string s, int nRows) { 2: // Start typing your C/C++ solution below 3: // DO NOT write int main() function 4: if(nRows <= 1) return s; 5: string result; 6: if(s.size() ==0) return result; 7: for(int i =0; i< nRows; i++) 8: { 9: for(int j =0, index =i; index < s.size(); 10: j++, index = (2*nRows-2)*j +i) 11: { 12: result.append(1, s[index]); //red element 13: if(i ==0 || i == nRows-1) //green element 14: { 15: continue; 16: } 17: if(index+(nRows- i-1)*2 < s.size()) 18: { 19: result.append(1, s[index+(nRows- i-1)*2]); 20: } 21: } 22: } 23: return result; 24: }
相关文章推荐
- [LeetCode 解题报告]006.ZigZag Conversion
- Leetcode<6 ZigZag Conversion>解题报告
- 【LeetCode】ZigZag Conversion 解题报告
- LeetCode解题报告—— 2 Keys Keyboard & Longest Palindromic Substring & ZigZag Conversion
- LeetCode ZigZag Conversion 解题报告
- [LeetCode] ZigZag Conversion 解题报告
- [LeetCode] ZigZag Conversion 解题报告
- LeetCode(6) ZigZag Conversion解题报告
- LeetCode: ZigZag Conversion 解题报告
- [leetcode] 281. Zigzag Iterator 解题报告
- 【LeetCode】 Binary Tree Zigzag Level Order Traversal 解题报告
- [Leetcode] 281. Zigzag Iterator 解题报告
- Leetcode 103. Binary Tree Zigzag Level Order Traversal 二叉树Zigzag遍历 解题报告
- [Leetcode]解题文档-ZigZag Conversion
- LeetCode解题报告—— Unique Binary Search Trees & Binary Tree Level Order Traversal & Binary Tree Zigzag Level Order Traversal
- [leetcode] 213. House Robber II 解题报告
- leetcode笔记--ZigZag Conversion
- [leetcode] 348. Design Tic-Tac-Toe 解题报告
- [Leetcode] 467. Unique Substrings in Wraparound String 解题报告
- LeetCode-Contains Duplicate III-解题报告