码迷,mamicode.com
首页 > 其他好文 > 详细

字符串之字形排列

时间:2020-04-19 11:14:56      阅读:60      评论:0      收藏:0      [点我收藏+]

标签:class   win   字符串排列   ring   new   false   color   ++   print   

 

import java.util.*;
public class Client {
    public static void main(String[] args) {
        String str = "abcdefghijk";
        char[][] chars = strArr(str, 4);
        for (char[] ints : chars) {
            System.out.println(Arrays.toString(ints));
        }
    }

    /**
     * 字符串排列
     */
    static char[][] strArr(String str,int col) {
        char[] chars = str.toCharArray();
        int row = (chars.length - col) / (col - 1) + 2 ;
        char[][] arr = new char[row][col];

        int rowIndex = 0;
        int colIndex = 0;
        int charIndx = 0;
        boolean isAsc = true;
        while (charIndx < chars.length){
            arr[rowIndex][colIndex] = chars[charIndx];
            charIndx++;
            if(isAsc){
                colIndex++;
            }else {
                colIndex--;
            }
            if(isAsc && (colIndex >= col)){
                isAsc = false;
                colIndex -= 2;
                rowIndex++;
            }else if(!isAsc && (colIndex < 0)){
                isAsc = true;
                colIndex += 2;
                rowIndex++;
            }
        }
        return arr;
    }

}

 

结果

[a, b, c, d]
[g, f, e,  ]
[ , h, i, j]
[ ,  , k,  ]

 

字符串之字形排列

标签:class   win   字符串排列   ring   new   false   color   ++   print   

原文地址:https://www.cnblogs.com/dongma/p/12730293.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!