6.ZigZag Conversion(Easy)

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)


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".

  题意并不难了理解,就是对一个字符串进行一个重新排列按新的规则输出

My Solution

(Java) Version 1 Time: 71ms:

  确实是慢,我对这类找规律的题目的解法大体都是找到一个类似的规律,然后用if语句来补全

public class Solution {
    public String convert(String s, int numRows) {
        int length=s.length();
        if(numRows==1||length<=numRows)return s;
        int itemCount=2*numRows-2;
        System.out.println("itemCount="+itemCount);
        int count=length%itemCount==0?length/itemCount:length/itemCount+1;
        System.out.println("count="+count);
        StringBuffer sb=new StringBuffer();
        for(int i=0;i

(Java) Version 2 Time: ms (By medi):

  比我慢,纯粹是记一下不同的做法

public class Solution {
    public String convert(String s, int numRows) {
        String res="";
        List strow = new ArrayList<>();
        for(int i=0; i

你可能感兴趣的:(6.ZigZag Conversion(Easy))