Index: [Leetcode] leetcode key index (C++/JAVA/PYTHON/SQL)
Github:https://github.com/illuz/leetcode
006.zigzag_conversion (Easy)
links:
Title: https://oj.leetcode.com/problems/zigzag-conversion/
Code (GitHub): Https://github.com/illuz/leetcode
Test Instructions:
Arranges a string in a line that is written in horizontal order.
Analysis:
Direct simulation on the line.
Code: C + +:
Class Solution {Public:string convert (string s, int nRows) {if (nRows = = 1) return s;int step = nRows * 2-2, len = S.len Gth (); string ret = "";//First rowfor (int i = 0; i < Len; i + = step) ret + = s[i];for (int i = 1; i < nRows-1; i++) {for (int j = i; J < len; j + = Step) {ret + = S[j];if (j + (Step-i * 2) < len) ret + = S[j + (Step-i * 2)];}} Last rowfor (int i = nRows-1; i < len; i + = step) ret + s[i];return ret;}};
Java:
public class Solution {public string convert (String s, int nRows) { if (nRows = = 1) return s ; int step = nRows * 2-2, len = S.length (); String ret = ""; First row for (int i = 0; i < len; i + = Step) ret + = S.charat (i); for (int i = 1, i < nRows-1; i++) {for (int j = i; J < len; j + = Step) { ret + = S.charat (j); if (j + (Step-i * 2) < Len) ret + = S.charat (j + (Step-i * 2));} } Last row for (int i = nRows-1; i < len; i + = Step) ret + = S.charat (i); return ret; }}
Python:
Class solution: # @return A string def convert (self, S, nRows): if nRows = = 1: return s step = nRows * 2-2 # first row ret = S[::step] for I in range (1, nRows-1): for J in range (I, Len (s), step): ret + = S[j] if J + (Step-i * 2) < Len (s): ret + s[j + (Step-i * 2)] # last row ret + = s[nrows-1: : Step] return RET
[Leetcode] 006. ZigZag Conversion (Easy) (C++/java/python)