现在的位置: 首页 > 综合 > 正文

leetcode——ZigZag Conversion

2017年12月22日 ⁄ 综合 ⁄ 共 1070字 ⁄ 字号 评论关闭

题目:

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

思路:

该题属于模拟范畴,不难,但是需要注意边界的条件细节。

找出string下标和所在行数的关系。其中str数组需要能够随机访问到,这样在查找的时候可以直接根据下标关系在O(1)的时间复杂度中找到。

AC代码:

public String convert(String s, int nRows) {
        if(nRows==1)
            return s;
        char[] strs = s.toCharArray();
        LinkedList<Integer> head = new LinkedList<Integer>();
        head.add(0);
        for(int i=1;;i++){
            int h = i*(2*nRows-2);
            if(h<strs.length)
                head.add(h);
            else{
                head.add(h);
                break;
            }
        }
        StringBuilder sb = new StringBuilder("");
        for(int i=0;i<nRows;i++){
            for(Integer idx:head){
                if(idx-i>=0 && idx-i<idx && idx-i<strs.length && i<nRows-1){  //此处条件略复杂,针对重复下标和越界的判断进行处理
                    sb.append(strs[idx-i]);
                }
                if(idx+i>=idx && idx+i<strs.length)                           //<span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">此处条件略复杂,针对重复下标和越界的判断进行处理</span>
                    sb.append(strs[idx+i]);
            }
        }
        return sb.toString();
    }

抱歉!评论已关闭.