zoukankan      html  css  js  c++  java
  • LeetCode--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".

    问题描述:

    给出一个字符串和一个整数numRows,返回得到的zigzag 序列。

    解决方法:

        找规律,画出当numRows=3,4,5,6时的样子,然后找规律。

    通过观察发现,每行起始位置是有后期规律的,彼此间相差span=numRows + (numRows-2)个字符序列;

                        在非起始行与末尾行中,每个周期都需要加入一个额外的字符,与本次周期起始字符相差 n = numRows + (numRows-2) - i * 2个字符。

    程序如下:

    public class Solution {
        public String convert(String s, int numRows) {
            if(s.length()<=0 || numRows<=1)
                return s;
            
            String res = "";
            int span = numRows + (numRows-2);
            for(int i=0; i<numRows; i++){
                    String s1 = new String();
                    for(int j=i; j<s.length(); j=j+span){
                        s1 = s1 + s.charAt(j);
                        int span1 = numRows +(numRows-2) -2*i;
                        if(i>0 && i<numRows-1 && j+span1<s.length()){//如果是中间行,需要额外加字符
                            s1 = s1 + s.charAt(j+span1);
                        }
                    }
                    res = res + s1;
            }
            return res; 
        }
    }
  • 相关阅读:
    5月29 流程
    5月27 权限设置及功能
    5月26 留言板练习题
    5月24 文件操作
    5月23 文件上传及图片上传预览
    5月23 注册审核
    5月21 回话控制SESSION COOKIE
    5月21 汽车查询及批量删除----php方法
    5月21 练习AJAX的查看详细及批量删除
    5月20 三级联动
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/4620892.html
Copyright © 2011-2022 走看看