zoukankan      html  css  js  c++  java
  • LeetCode-ZigZag Conversion

    锯齿形排列

    其实就是找到规律就行。

    代码如下:

    package com.leetcode.study;
    
    
    public class Main {
        private int lo,maxLen;
    
        public static void main(String[] args) {
            String s = "AB";
            System.out.println(convert(s, 2));
            
    
        }
        public static String convert(String s, int numRows){
            if(numRows==1)return s;
            int len = s.length();
            if(numRows==2){
                StringBuffer sb1 = new StringBuffer();
                StringBuffer sb2 = new StringBuffer();
                for(int i = 0;i<len;i++){
                    if(i%2==1)sb1.append(s.charAt(i));
                    else sb2.append(s.charAt(i));
                }
                return sb2.append(sb1).toString();
            }
            int rows = len%(2*(numRows-1))==0?len/(2*(numRows-1)):1+len/(2*(numRows-1));
            StringBuffer sb = new StringBuffer();
            for(int i = 0;i<numRows;i++){
                if(i==0||i==(numRows-1)){
                    for(int j = 0;j<rows;j++){
                        if(2*(numRows-1)*j+i<len)sb.append(s.charAt((numRows+1)*j+i));
                    }
                }else{
                    for(int j = 0;j<rows;j++){
                        if(2*(numRows-1)*j+i<len)sb.append(s.charAt(2*(numRows-1)*j+i));
                        if(2*(numRows-1)*(j+1)-i<len)sb.append(s.charAt(2*(numRows-1)*(j+1)-i));
                    }
                }
            }
            return sb.toString();
            
        }
        
    }
  • 相关阅读:
    16. 3Sum Closest
    17. Letter Combinations of a Phone Number
    20. Valid Parentheses
    77. Combinations
    80. Remove Duplicates from Sorted Array II
    82. Remove Duplicates from Sorted List II
    88. Merge Sorted Array
    257. Binary Tree Paths
    225. Implement Stack using Queues
    113. Path Sum II
  • 原文地址:https://www.cnblogs.com/LoganChen/p/8806750.html
Copyright © 2011-2022 走看看