码迷,mamicode.com
首页 > 其他好文 > 详细

ZigZag Conversion

时间:2014-12-18 20:25:04      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:style   blog   ar   io   color   os   sp   for   java   

  题目:

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

这道题应该算是比较简单的吧,题目也没什么歧义。我最怕就是题目没理解清楚。我刚看到这道题目第一个想法就是找规律了,猜出随着nRows的变化,第一行的每一个字符和nRows是一个什么样的关系。这种找规律的具体方法我就不说了。我这里想的是如果我能够将每个将这种结构转换成一种数据结构那存取就方便了。这是我的第一个想法,可是我想不到怎么去构造这种数据结构。之后我就觉得我可以把这些字符按一定规则存到某个集合中,然后在按一定规则取出即可。具体一点就是我能将上诉的第一行PAHN存到一个list中,将第二行APLSIIG存到第二个list中,将第三行存到第三个list中。这样我输出就只需要按照list的顺序来输出就可以了。思想大致是这样。代码如下

import java.util.ArrayList;
/**
 * Created by fage on 2014/12/16.
 * ZigZag Conversion
 */
public class Solution {
    public String convert(String s, int nRows) {
        if(nRows == 1){
            return s;
        }
        String[] split = s.split("");
        int len = s.length();
        int period = 2*nRows-2;
        int col = len/period;
        int rem = len%period;
        int point = 1;
        int check = 0;
        StringBuffer res = new StringBuffer();
//因为涉及到字符串的多次相加,装箱和拆箱会大大影响效率,所以用这个类来避免
        ArrayList<StringBuffer> arr = new ArrayList<StringBuffer>(nRows);
        for(int i=0;i<nRows;i++){
            arr.add(new StringBuffer());
        }
//核心代码,把字符分别存到每一行的list中
        for(int i=0;i<col;i++){
            for(int j=0;j<nRows;j++){
                if(j==0 || j==nRows-1) {
                    arr.get(j).append(split[point]);
                    check = (nRows - 2) * 2;
                }
                else{
                    arr.get(j).append(split[point]).append(split[point+check]);
                    check-=2;
                }
                point++;

            }
            point = (i + 1) * period+1;

        }
//主要是为了考虑一些特殊情况
        for(int i=0;i<rem;i++){
            if(i < nRows) {
                arr.get(i).append(split[len - rem + i + 1]);
                check = 1;
            }else{
                arr.get(nRows-check-1).append(split[len - rem + i + 1]);
                check++;
            }
        }
//生产最终的字符串
        for(int i=0;i<nRows;i++){
            res.append(arr.get(i));
        }
        return res.toString();
    }
    public static void main(String[] args){
        System.out.println(new Solution().convert("ABCDE", 4));
    }
}

ZigZag Conversion

标签:style   blog   ar   io   color   os   sp   for   java   

原文地址:http://www.cnblogs.com/fage520/p/4172577.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!