6. ZigZag Conversion 之字形字符判断

来源:互联网 发布:行业大数据 编辑:程序博客网 时间:2024/05/16 08:07

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   NA P L S I I GY   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".


不做评论,只做转发,不知道之字形是怎么个写法,白白浪费了我的时间。看看之字形状,见这篇http://blog.csdn.net/zhouworld16/article/details/14121477

因为如果知道了之字形后,题目本身就没有任何难度了,不研究了,直接拷贝代码通过

http://blog.csdn.net/xudli/article/details/8423097

public class Solution {
    public String convert(String s, int nRows) {
        if(nRows<=1 || s.length()<=nRows) return s;
        
        int len = s.length();
        StringBuilder sb = new StringBuilder();  //使用了StringBuilder,非线程安全
        for(int i=0; i<nRows; i++) {
            int j=i;
            while(j<len) {
                sb.append(s.charAt(j));  //StringBuilder里边是append方法
                if(i!=0 && i!=nRows-1) {
                    if(j + 2*(nRows-1-i) < len)  sb.append(s.charAt(j + 2*(nRows-1-i) ) );
                }
                j += 2*(nRows-1);
            }
        }
        return sb.toString();   //StringBuilder通过toString转换为string
    }
}

0 0
原创粉丝点击