ZigZag Conversion

本贴最后更新于 2342 天前,其中的信息可能已经时异事殊

题目描述

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

ZigZag 是这个意思:

ZigZag

解题思路

研究后发现:

  • numRows==1 时,直接返回 s;
  • numRows > 1 时,第一行的数字索引为差值为 2*numRows-2
    • 所以相应第二行的索引为第一行索引'+/-1';
    • 第三行索引是'+/-2';
    • ...

代码

class Solution {
    public String convert(String s, int numRows) {
        if (s == null || s.length() == 0 || numRows == 1)
            return s;
        StringBuilder ret = new StringBuilder();
        for (int i = 0; i < numRows; i++) {
            for (int j = 0; j < s.length()+(2*numRows-2); j = j+(2*numRows-2)) {
                if (j != 0 && i != 0 && i < numRows-1 && j-i < s.length())
                    ret.append(s.charAt(j-i));
                if (j+i < s.length())
                    ret.append(s.charAt(j+i));
            }
        }
        return ret.toString();
    }
}
  • 算法
    394 引用 • 254 回帖 • 22 关注
  • LeetCode

    LeetCode(力扣)是一个全球极客挚爱的高质量技术成长平台,想要学习和提升专业能力从这里开始,充足技术干货等你来啃,轻松拿下 Dream Offer!

    209 引用 • 72 回帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...