顺时针旋转给定的字符串布局

时间:2015-04-23 02:19:39

标签: java

给定以下形式的String布局:

X......X
....X..X
....X..X

顺时针旋转上面的布局90度,应该是:

..X
...
...
...
XX.
...
...
XXX 

将String字符顺时针旋转90度的最简单方法是什么? String布局可以是任何形式和任何大小。如果我有100000x100000大小的字符串布局怎么办?

public String rotate(String layout)

public void rotate(String layout)

3 个答案:

答案 0 :(得分:1)

修改

我修正了OP在下面的评论中指出的错误。这应该完全符合上述原始问题的要求。

 public static String rotateStringMatrixBy90(String matrix) {
    int numberOfRows = 3; // this I leave as an exercise
    int numberOfColumns = 8; // same with this one

    String newMatrix = "";

    int count = 0;
    String[] newMatrixColumns= matrix.split("\n");
    while (count < matrix.split("\n")[0].length()) {
        for (int i = newMatrixColumns.length - 1; i > -1; i--) {
            newMatrix = newMatrix + newMatrixColumns[i].charAt(count);
        }

        newMatrix = newMatrix + "\n";
        count++;
    }

    return newMatrix;
 }

这就是你如何使用它:

    String m = "X......X\n" +
               "....X..X\n" +
               "....X..X";

    System.out.println(m);

    m = rotateStringMatrixBy90(m);
    System.out.println(m);

(注意:这假设您使用\ n作为行之间的分隔符):

答案 1 :(得分:0)

修改:刚看到你想要一个String作为arg

你可以用这个:

public class SO {
    public static void main(String[] args) throws Exception {
        String string = "X......X\n" +
                        "....X..X\n" +
                        "....X..X\n";

        System.out.println(string);
        string = rotateClockwise(string);
        System.out.println(string);
    }

    static String rotateClockwise(String input) {
        String[] arr = input.split("\n");
        int length = arr[0].length();
        String[] ret = new String[length];
        for (int i = 0; i < ret.length; i++) {
            ret[i] = "";
        }

        for (int i = arr.length-1; i >= 0; i--) {
            char[] chars = arr[i].toCharArray();

            for (int j = 0; j < ret.length; j++) {
                ret[j] += chars[j];
            }
        }
        String output = "";
        for (String str: ret)
            output += str + "\n";

        return output;
    }
}

请注意,这有错误检查。

答案 2 :(得分:0)

public static String[] rotate(String[] originalArray) {
    String[] rotatedArray = new String[originalArray[0].length()];
    for (int i=0;i<rotatedArray.length;i++) {
        rotatedArray[i]="";
    }
    for (int j = 0; j < originalArray[0].length(); j++) {
        for (int i = originalArray.length - 1; i >= 0; i--) {
            rotatedArray[j] += originalArray[i].charAt(j);
        }
    }
    return rotatedArray;
}