leetcode 6 ZigZag Conversion

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 idea is, the first row and last row has no offset. Each element has a fixed difference of 2(nRows-1); For the rows in between, there is a incremental offset of 2;

0 6 12 -> distance = 2(nRows-1) = 6 offset = 0
1 5 7 11 -> offset = distance - 2 = 4
2 4 8 10 -> offset = distance -2 -2 = 2
3 9 -> distance = 2(nRows-1) = 6 offset = 0

Easy to observe. There is a catch, that you need to add the offset element with previous regular element. 5 follows 1, 4 follows 2. Otherwise, you will miss the tail if there is no vertical column in the end.Looks like a CS homework:)

class Solution {
public:
    string convert(string s, int nRows) {
        if(s.length() == 0 ||
            s.length()/nRows < 1 ||
            nRows == 1)
        {
            return s;
        }
        int distance = 2*(nRows-1);
        string result;
        int offset = 0;
        for (int row = 0; row < nRows; row++)
        {
            for (int index = row; index < s.length(); index += distance)
            {
                result+=s[index];
                if (offset != 0 && index + distance - offset < s.length())
                {
                    result+=s[index + distance - offset];
                }
            }
            offset += 2;
            offset = offset % distance;
        }
        return result;
    }
};

解决方案2:

The problem statement itself is unclear for many. Especially for 2-row case. “ABCD”, 2 –> “ACBD”. The confusion most likely is from the character placement. I would like to extend it a little bit to make ZigZag easy understood.

The example can be written as follow:
1.P…….A……..H…….N
2…A..P….L..S….I…I….G
3…..Y………I……..R

Therefore,

class Solution {
public:
    string convert(string s, int numRows)
    {

    if (numRows <= 1)
        return s;

    const int len = (int)s.length();
    string *str = new string[numRows];

    int row = 0, step = 1;
    for (int i = 0; i < len; ++i)
    {
        str[row].push_back(s[i]);

        if (row == 0)
            step = 1;
        else if (row == numRows - 1)
            step = -1;

        row += step;
    }

    s.clear();
    for (int j = 0; j < numRows; ++j)
    {
        s.append(str[j]);
    }

    delete[] str;
    return s;
}
};

python解决方案:
The idea is to use the remainder (index%period) to determine which line the character at the given index will be. The period is calculated first based on nRows. A dictionary with remainder:line as key:value is then created (this can also be done with a list or a tuple). Once these are done, we simply go through s, assign each character to its new line, and then combine these lines to get the converted string.

The code may be further shortened by using dict comprehension:

d={i:i if i

def convert(self, s, nRows):
    if nRows==1:
        return s
    period= 2*(nRows -1)
    lines=["" for i in range(nRows)]
    d={} # dict remainder:line
    for i in xrange(period):
        if i<nRows:
            d[i]=i
        else:
            d[i]=period-i

    for i in xrange(len(s)):
        lines[ d[i%period] ] +=s[i]

    return "".join(lines)
时间: 2025-01-20 12:49:33

leetcode 6 ZigZag Conversion的相关文章

LeetCode 6 ZigZag Conversion(Z型转换)

翻译 字符串"PAYPALISHIRING"通过一个给定的行数写成如下这种Z型模式: P A H N A P L S I I G Y I R 然后一行一行的读取:"PAHNAPLSIIGYIR" 写代码读入一个字符串并通过给定的行数做这个转换: string convert(string text, int nRows); 调用convert("PAYPALISHIRING", 3),应该返回"PAHNAPLSIIGYIR".

ZigZag Conversion

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: "PAHNAPLSII

&lt;font color=&quot;red&quot;&gt;[置顶]&lt;/font&gt;

Profile Introduction to Blog 您能看到这篇博客导读是我的荣幸,本博客会持续更新,感谢您的支持,欢迎您的关注与留言.博客有多个专栏,分别是关于 Windows App开发 . UWP(通用Windows平台)开发 . SICP习题解 和 Scheme语言学习 . 算法解析 与 LeetCode等题解 . Android应用开发 ,而最近会添加的文章将主要是算法和Android,不过其它内容也会继续完善. About the Author 独立 Windows App 和

leetcode难度及面试频率

转载自:LeetCode Question Difficulty Distribution               1 Two Sum 2 5 array sort         set Two Pointers 2 Add Two Numbers 3 4 linked list Two Pointers           Math 3 Longest Substring Without Repeating Characters 3 2 string Two Pointers      

LeetCode总结【转】

转自:http://blog.csdn.net/lanxu_yy/article/details/17848219 版权声明:本文为博主原创文章,未经博主允许不得转载. 最近完成了www.leetcode.com的online judge中151道算法题目.除各个题目有特殊巧妙的解法以外,大部分题目都是经典的算法或者数据结构,因此做了如下小结,具体的解题思路可以搜索我的博客:LeetCode题解 题目 算法 数据结构 注意事项 Clone Graph BFS 哈希表 Word Ladder II

LeetCode All in One 题目讲解汇总(持续更新中...)

终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 如果各位看官们,大神们发现了任何错误,或是代码无法通过OJ,或是有更好的解法,或是有任何疑问,意见和建议的话,请一定要在对应的帖子下面评论区留言告知博主啊,多谢多谢,祝大家刷得愉快,刷得精彩,刷出美好未来- 博主制作了一款iOS的应用"Leetcode Meet Me",里面有Leetcode上所有的题目,并且贴上了博主的解法,随时随地都能

[LeetCode]103.Binary Tree Zigzag Level Order Traversal

[题目] Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary tree {3,9,20,#,#,15,7}, 3 / \ 9 20 / \ 15 7 retur

在leetcode上提交zigzag后,一直爆出RE错误,感觉应该没有越界?

问题描述 在leetcode上提交zigzag后,一直爆出RE错误,感觉应该没有越界? RT,原题在这:https://oj.leetcode.com/problems/zigzag-conversion/ 很简单的一个程序,就是横排字符串改成折线字符串,然后横排输出 我的程序在VS2012上 debug模式下自己测试没找到错误,但是提交上去之后, 就报Runtime-error,百思不得其解,求大神指教解救! char *convert(char *s, int nRows) { long l

[LeetCode]8. String to Integer (atoi)

[题目] 点击打开链接 Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. Notes: It is intended for this probl