LeetCode---(6)ZigZag Conversion

转载 2015年07月10日 19:59:19

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".

主要是3个公式:
1 之字形行数为nRows,那么每次重复样出现前的间隔字符为zigSpan = nRows*2-2;
2 第一行和最尾一行都是存放一个字符的,所以存储的字符为间隔为zigSpan的字符
3 中间行是需要额外存储多一个字符的,存储的字符位置是: zigSpan + j - 2*i
class Solution {
public:
    string convert(string s, int numRows) {
        if(numRows<=1||s.size()==0)
            return s;
        string res;
        int zigSpan = numRows*2-2;
        for(int i=0;i<numRows;i++)
        {
            for(int j=i;j<s.size();j+=zigSpan)
            {
                res.push_back(s[j]);
                if(i!=0&&i!=numRows-1&&zigSpan+j-2*i<s.size())
                    res.push_back(s[zigSpan+j-2*i]);
            }
        }
        return res;
    }
};



LEETCODE 6 ZigZag Conversion JAVA

LEETCODE JAVA题解 第六题

LeetCode之6---ZigZag Conversion

题目:      The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like...

leetcode 6. ZigZag Conversion-Zizag转换

原题链接:6. ZigZag Conversion 【思路1】 public String convert(String s, int numRows) { if(numR...

leetcode_6_ZigZag Conversion

思路: 想了好久,思维总是局限在二维数组,找字符串的长度和二维数组的行列数之间的某种联系,想了好久,没有思路。 然后,然后就上网看了一下,有一种思路说是用字符串数组即可,就想到了StringBuil...

LeetCode-6(ZigZag Conversion)

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (yo...

[leetcode: Python]6. ZigZag Conversion

The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you...
  • NXHYD
  • NXHYD
  • 2017年05月18日 17:33
  • 365

LeetCode OJ-6.ZigZag Conversion

LeetCode OJ-6.ZigZag Conversion题目描述 The string "PAYPALISHIRING" is written in a zigzag pattern on ...

《LeetBook》leetcode题解(6): ZigZag Conversion[E]

006.ZigZag Conversion[E]ZigZag ConversionE 题目 思路1用字符串数组 思路2观察规律题目The string “PAYPALISHIRING” is writ...

Leetcode 6 ZigZag Conversion

ZigZag Conversion The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of ...

LeetCode题目:6. ZigZag Conversion Add to List

题目原址:点击打开链接 题目描述:The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of row...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode---(6)ZigZag Conversion
举报原因:
原因补充:

(最多只允许输入30个字)