Skip to content

Latest commit

 

History

History
91 lines (78 loc) · 2.22 KB

杨新峰-20180907.md

File metadata and controls

91 lines (78 loc) · 2.22 KB

【leetcode 算法题】

ZigZag Conversion

/**
 * @author yangxf 
 *         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 s, int numRows); Example 1:
 * 
 *         Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR"
 *         Example 2:
 * 
 *         Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI"
 *         Explanation:
 * 
 *         P     I     N 
 *         A   L S   I G 
 *         Y A   H R 
 *         P     I
 * 
 *
 */
class Solution {
    public static String convert(String s, int numRows) {
        if(numRows<=1){
            return s;
        }
        Character[][] characters = new Character[numRows][s.length()];
        int col = 0, row = 0,flag=1;
        for (int i = 0; i < s.length(); i++) {
            characters[row][col] = s.charAt(i);
            if (row >= numRows - 1 || (col > 0 && row == 0 && i<s.length()-1)) {
                col++;
            }
            if(row<=0) {
                flag=1;
            }
            if (row >= numRows - 1) {
                row--;
                flag=-1;
            } else {
                if(flag>0) {
                    row++;
                }else {
                    row--;

                }
            }

        }
        StringBuilder ret = new StringBuilder();
        for (int i = 0; i < numRows; i++) {
            for (int j = 0; j < s.length(); j++) {
                if (characters[i][j] != null) {
                    ret.append(characters[i][j]);
                }
            }
        }

        return ret.toString();
    }
}

Z字形打印字符串的算法题想的时间挺长的,一直没想出来好的方法。

【英文文章】

暂无

【技术技巧】

暂无

【技术分享】

暂无