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();
        }
    }
    
  • 相关阅读:
    字符串与字典常用命令
    Python学习之路:字符串常用操作
    Python学习之路:购物车实例
    面试题2017
    c#语法学习
    结构化设计模式-桥接模式
    结构型设计模式-适配器模式
    .Net Cache
    设计模式的六大原则
    uml类图关系
  • 原文地址:https://www.cnblogs.com/zihaowang/p/4455823.html
Copyright © 2011-2022 走看看