Last active
September 23, 2017 23:22
-
-
Save BiruLyu/485c7664e8d81613ee1d7e23802642c5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | | |
| """ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment