zoukankan      html  css  js  c++  java
  • Leetcode 6. ZigZag Conversion(找规律,水题)

    6. ZigZag Conversion
    Medium

    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

    (之字型)

     1 class Solution {
     2 public:
     3     string convert(string s, int numRows) {
     4         int len = s.length();
     5         string ans;
     6         if(numRows==1) return s;
     7         for(int i = 0;i < numRows; i++){
     8             int left = (numRows-1-i)*2;
     9             int right = (i)*2;
    10             int cnt = i;
    11             int flag = 1;
    12             while(cnt < len){
    13                 flag = (flag+1)%2;
    14                 if((left==0 && flag==0)||(right==0&&flag==1)) continue;
    15                 ans+=s[cnt];
    16                 if(flag==0) cnt = cnt+left;
    17                 else cnt = cnt+right;
    18             }
    19         }
    20         return ans;
    21     }
    22 };
  • 相关阅读:
    Git
    java类加载
    DES-加解密C语言实现
    Android消息队列初识 && ThreadLocl 简述
    DbUTils
    JDBC(二)
    jdbc工具类
    JDBC(一)
    数据库
    MySQL数据库学习: 01 —— 数据库的概述
  • 原文地址:https://www.cnblogs.com/shanyr/p/11419397.html
Copyright © 2011-2022 走看看