Monday, May 27, 2013

ZigZag Conversion @Leetcode

刷题必备书籍Cracking the Coding Interview: 150 Programming Questions and Solutions 

简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career
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".

The key point of this problem is to find the pattern of index of the output array. Here we can divide the problem in two part, the first part is rows without Zag and the rows in the middle that have Zag. The total number of rows is nRows. The number of rows has Zag is nRows-2. So when we designing the loop in the algorithm, we can put a judging condition as if(i>0&&i<nRows-1) then do..., it means the rows we are working on are in the middle. Then we output the chars row by row. Let's define the new output string as string ret. First of all, let's consider the first row, the elements will be added in ret consequently are s[0], s[0+zigsize], s[0+2*zigsize]..until reach the end. Then set the counter i=1, it points to the second row. The first element in second row is s[1], the second element in second row is s[1+zigsize-2*1]. The gap between each two zag element in a row is zigsize. Once we figure out this regularity, we can design the algorithm based on this. 

Here is the link that well-solved this problem.
http://blog.unieagle.net/2012/11/08/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Azigzag-conversion/

No comments:

Post a Comment

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...