LintCode算法题 1363. 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)
Z型输出的字符串

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 s, int numRows);

convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.

思路

如果numRows为1,直接返回原字符串。如果是多行,用和行数相同数量的StringBuilder保存对应的每行的结果,再将这些StringBuilder按顺序拼接起来输出。在往StringBuilder中保存字符的过程中,用一个int型变量保存行号,用一个boolean型变量来确认下一次保存字符应该在第几行对应StringBuilder。

代码

public class Solution {
    /**
     * @param s: the given string
     * @param numRows: the number of rows
     * @return: the string read line by line
     */
    public String convert(String s, int numRows) {
        if(numRows<=1||s==null){
            return s;
        }else{
            List<StringBuilder> builderList = new ArrayList<>();
            for(int i = 0; i < numRows; i++){
                StringBuilder sb = new StringBuilder();
                builderList.add(sb);
            }
            char[] sCharArray = s.toCharArray();
            int j = 0;
            boolean raise = true;
            for (int i = 0; i < sCharArray.length; i++){
                char c = sCharArray[i];
                builderList.get(j).append(c);
                if(raise){
                    j++;
                    if(j == numRows - 1){
                        raise = false;
                    }
                }else{
                    j--;
                    if(j == 0){
                        raise = true;
                    }
                }
            }
            StringBuilder result = new StringBuilder();
            for(StringBuilder sb : builderList){
                result.append(sb);
            }
            return result.toString();
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值