leetcode six Z-shaped brush title notes conversion Scala version

leetcode six Z-shaped brush title notes conversion Scala version

Source Address: (leetcode title notes six Z-shaped brush Scala converted version) [ https://leetcode.com/problems/zigzag-conversion/submissions/ ]

Problem Description:

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

Brief analysis ideas:

A direction indicator setting parameters layers, performed by determining whether the top or bottom, the direction changes, the layer corresponding to the character string into the array corresponding to the last string array will be summarized.

Code added:

object Solution {
    def convert(s: String, numRows: Int): String = {
         if (numRows == 1 || s.length <= numRows) return s

      var upDown = true
      var counter = 0
      var arr:Array[String] = new Array[String](numRows)
      var answer = ""


      for (i <- 0 until s.length){
        //println("--------------------------")
        //println("i: " + i.toString)
        //println("counterPre: "+counter.toString)
        //println("upDownPre: "+upDown.toString)
        arr(counter) += s.charAt(i)
        /* 用match不可以。。 神秘
        (counter) match{
          case(0) => upDown = true
          case(maxCounter) => upDown = false
        }
        */
        if (counter == 0) upDown = true
        if (counter == numRows-1) upDown = false
        (upDown) match{
          case(true) => counter+=1
          case(false) => counter-=1
        }
        //println("counterAfter: "+counter.toString)
        //println("upDownAfter: "+upDown.toString)
        //println("s(i): " + s.charAt(i))
      }

      for (i <- 0 until numRows){
        answer += arr(i).drop(4).toString
        //println(arr(i))
    }
     return answer
    }
}

Guess you like

Origin www.cnblogs.com/ganshuoos/p/12657444.html