zoukankan      html  css  js  c++  java
  • 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();
        }
    }
    
  • 相关阅读:
    更改SQLServer实例默认字符集
    使用DMV排查数据库系统异常
    OD使用符号文件进行源码级调试问题
    申请博客园第一天
    各种mac软件地址
    第6条:理解“属性”
    提高代码质量的几个方法!52个,先罗列几个自己看
    Item2的使用
    MAC命令大全
    PV UV IP
  • 原文地址:https://www.cnblogs.com/zihaowang/p/4455823.html
Copyright © 2011-2022 走看看