• 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();
        }
    }
    
  • 相关阅读:
    html5--6-56 阶段练习5-翻转效果
    html5--6-55 动画效果-关键帧动画
    html5--6-53 阶段练习4-画廊
    html5--6-52 动画效果-过渡
    navicat常用快捷键
    Mysql语句示例
    mysql语句大全
    intellij IDEA怎样打war包
    如何将java web项目上线/部署到公网
    jsp的4大作用域
  • 原文地址:https://www.cnblogs.com/zihaowang/p/4455823.html
Copyright © 2020-2023  润新知