java 6. ZigZag Conversion.java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 6. ZigZag Conversion.java相关的知识,希望对你有一定的参考价值。


class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        res = "";
        if not s:
            return res;
        
        if numRows == 1 or len(s) <= numRows :
            return s;
        
        l = numRows;
        temp = 0;
        while(temp < len(s)):
            res += s[temp];
            temp += l + l - 2;
        for i in range(1, numRows - 1): # except the fist and the last row, each row add character :Odd-even alternation
            res += s[i];
            #col = 1;
            j = i;
            col = 0;
            while(j < len(s)):
            
                diff = ((l - 1) - i) + ( ( l - 2 ) - i ) + 1;
                j = j + diff;
                if (j < len(s)):
                    res += s[j];
                    diff = ( (i - 1) + ( i - 0) + 1);
                    j = j + diff;
                    if (j < len(s)):
                        res += s[j];
        
        temp = l - 1;
        while(temp < len(s)):
            res += s[temp];
            temp += l + l - 2;
                
        
        return res;

"""
Your input   | Expected answer

"0123456789" | "0123456789"  ### Note:if numRows > len(s): return s;
11           |
"0123456789" | "0481357926"
3            |
"0123456789" | "0615724839"
4            |
"0123456789" | "0817926354"
5            |
"0123456789" | "0192837465"
6            |
""           | ""
0            |
"""
                    
public class Solution {
    public String convert(String s, int numRows) {
        //String res = "";
        if(s == null || s == "" || numRows == 1) return s;
        //String[] eachRow = new String[numRows];
        StringBuilder[] eachRow = new StringBuilder[numRows];
        for (int i = 0; i < eachRow.length; i++) eachRow[i] = new StringBuilder();// Initialization!!!!
        int direct = -1;
        int j = 0;
        for(int i = 0; i < s.length(); i++){
            if(j == 0 || j == numRows - 1 ){
                direct *= -1;
            }
            eachRow[j].append(s.charAt(i));
            j += direct;
        }
        for(int i = 1; i < numRows; i++){
            eachRow[0].append(eachRow[i]);
        }
        return eachRow[0].toString();
    }
}

以上是关于java 6. ZigZag Conversion.java的主要内容,如果未能解决你的问题,请参考以下文章

java 6. ZigZag Conversion.java

java 6. ZigZag Conversion.java

java 6. ZigZag Conversion.java

java 6. ZigZag Conversion.java

java6. ZigZag Conversion

Leetcode 6. ZigZag Conversion