• Java [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".

    解题思路:

    注意到zigzag的字符串按照读写的顺序是来回分配给不同行的,所以存在取模值的问题,对于正着往下读的字符串,对(nRows-1)取模值的结果刚好是它对应的行数,而对于往上读取的情况,对(nRows-1)取模的结果加上行号刚好等于(nRows-1)。所以考虑用boolean变量记录方向。对于每一行设立StringBuilder对象,适合向其末尾追加值。

    代码如下:

    public class Solution {
        public String convert(String s, int nRows) {
            StringBuilder[] stringBuilder = new StringBuilder[nRows];
    		for(int i = 0; i < nRows; i++)
    			stringBuilder[i] = new StringBuilder();
    		boolean reverse = true;
    		if(nRows == 1)
    			return s;
    		if (s.length() == 1)
    			return s;
    		for(int i = 0; i < s.length(); ++i){
    			if(i % (nRows - 1) == 0)
    				reverse = !reverse;
    			if(! reverse){
    				stringBuilder[i % (nRows - 1)].append(s.charAt(i));
    			}
    			else{
    				stringBuilder[nRows - 1 -(i % (nRows - 1))].append(s.charAt(i));
    			}
    		}
    		for(int i = 1; i < nRows; i++){
    			stringBuilder[0].append(stringBuilder[i]);
    		}
    		return stringBuilder[0].toString();
        }
    }
    
  • 相关阅读:
    echarts 折线图(移动端)X轴显示不全
    文字超出省略号类型
    逻辑运算为true
    13年省赛总结
    PyCharm专业版破解教程
    django之定义统一返回数据格式与GET/POST装饰器
    Xmind8破解教程
    django之mysqlclient安装
    django之“static”全局设置
    django之集成第三方支付平台PaysAPI与百度云视频点播服务接入
  • 原文地址:https://www.cnblogs.com/zihaowang/p/4455823.html
Copyright © 2020-2023  润新知