LeetCode算法题之第6题ZigZag Conversion

Question:

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

解决:

输出为Z形状的字符串。

public String convert(String s, int numRows) {
    int temp = 2 * numRows - 2;
    String result[] = new String[numRows];
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < numRows; ++i){
        result[i] = "";
    }
    for (int i = 0; i < s.length(); ++i){
        if (temp != 0)
            result[i%temp >= numRows ? temp-i%temp:i%temp] += s.charAt(i);
        else
            result[temp] += s.charAt(i);
    }
    for (int i = 0; i < result.length; ++i){
        sb.append(result[i]);
    }
    return sb.toString();
}

代码地址(附测试代码):
https://github.com/shichaohao/LeetCodeUsingJava/tree/master/src/zigZagConversion

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 11,540评论 0 23
  • 太阳山顶, 最是一年春好处。 微风如沐, 静观澜山云卷舒。 休辞醉倒, 花不看开人易老。 莫待春回, 一寸光阴不可轻。
    恰恰好sir阅读 351评论 0 1
  • 父母真的是最包容我们的人。自己情绪不好就会伤害了身边亲近的人,想想自己也挺糟糕的。还是要收着点情绪,不要因为其他人...
    就是BRHX阅读 139评论 0 0
  • 建筑工程文件管理规程 (施工分册) 1总则 1.0.1为提高城乡建设工程质量,提高施工过程控制,完善工程技术资料,...
    个人世界阅读 253评论 0 1

友情链接更多精彩内容