LeetCode - Algorithms
  • Introduction
  • 1. Two Sum
  • 2. Add Two Numbers
  • 3. Longest Substring Without Repeating Characters
  • 4. Median of Two Sorted Arrays
  • 5. Longest Palindromic Substring
  • 6. ZigZag Conversion
  • 7. Reverse Integer
  • 8. String to Integer (atoi)
  • 9. Palindrome Number
  • 10. Regular Expression Matching
  • 11. Container with Most Water
  • 12. Integer to Roman
  • 13. Roman to Integer
  • 14. Longest Common Prefix
  • 15. 3Sum
  • 16. 3Sum Closest
  • 17. Letter Combinations of a Phone Number
  • 18. 4Sum
  • 19. Remove Nth Node From End of List
  • 20. Valid Parentheses
  • 21. Merge Two Sorted Lists
  • 22. Generate Parentheses
  • 23. Merge k Sorted Lists
  • 24. Swap Nodes in Pairs
  • 25. Reverse Nodes in k-Group
  • 26. Remove Duplicates from Sorted Array
  • 27. Remove Element
  • 28. Implement strStr()
  • 29. Divide Two Integers
  • 30. Substring with Concatenation of All Words
  • 31. Next Permutation
  • 32. Longest Valid Parentheses
  • 33. Search in Rotated Sorted Array
  • 34. Search for a Range
  • 35. Search Insert Position
  • 36. Valid Sudoku
  • 37. Sudoku Solver
  • 38. Count and Say
  • 39. Combination Sum
Powered by GitBook
On this page
  • Problem
  • Analysis
  • Code

6. ZigZag Conversion

Problem

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 text, int nRows);

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

Related Topics:

String

Analysis

  [ 0]            [ 6]            [12]          
  [ 1]      [ 5]  [ 7]      [11]  [13]    
  [ 2]  [ 4]      [ 8]  [10]      [14]
  [ 3]            [ 9]            [15]

可以发现:

  • 每一完整的列,其差值为 2 * numRows - 2。

  • 斜线左右分割这差值,其上下层之间,分割的差值 ±2。

Code

class Solution {

    fun convert(s: String, numRows: Int): String {

        if (numRows == 1) {
            return s
        }

        val dvalue = IntArray(2)
        dvalue[0] = 2 * numRows - 2

        val ns = CharArray(s.length)
        var index = 0
        var j: Int
        var df: Int

        val limit = minOf(s.length, numRows)
        for (i in 0 until limit) {

            j = i
            df = 1
            while (j < s.length) {

                ns[index++] = s[j]

                df = (df + 1) % 2
                df = if (dvalue[df] == 0) (df + 1) % 2 else df
                j += dvalue[df]
            }

            dvalue[0] -= 2
            dvalue[1] += 2
        }

        return String(ns)
    }
}
Previous5. Longest Palindromic SubstringNext7. Reverse Integer

Last updated 6 years ago