[英]Rotating a String or char clockwise by 90 degrees
伙計們,我很難過將Shape順時針旋轉90度。 我在完成它時遇到了麻煩。 如果有形狀:
.t.
ttt
方法rotateBy90()
將上述形狀順時針旋轉90度,因此將顯示以下內容:
t.
tt
t.
形狀是String
類型。 在這里,我所擁有的和我非常確定我完全做錯了。 該方法可以通過使用char[][]
或char[]
或String[]
或String[][]
。 另一個問題是rotateBy90()
是一個void
方法。 smb可以幫我這個旋轉算法嗎? 提前致謝!
import java.util.*;
public class CreateShape {
private int height;
private int width;
private char dc;
private Rotation initialPos;
private Rotation nextPos;
private char[][] shape = new char[height][width];
String[] shapeLayout = new String[height];
String[] rotatedArray;
public CreateShape(int height, int width, char dc)
{
this.height = height;
this.width = width;
this.dc = dc;
initialPos = Rotation.CW0;
}
public void rotateBy90()
{
nextPos = initialPos.next();
String newLayout = "";
int count = 0;
String[] newMatrixColumns= shape.split("\n");
while (count < shape.split("\n")[0].length()) {
for (int i = newMatrixColumns.length - 1; i > -1; i--) {
newLayout += newMatrixColumns[i].charAt(count);
}
newLayout = newLayout + "\n";
count++;
}
}
我不太了解您的方法以及您遇到的困難所在。 我也不明白為什么您有這么多未使用的字段。 您可能需要將width
和height
字段設置為final
,因為在這種情況下,它們實際上不應更改。
我個人認為到目前為止,最簡單的方法是使用char[][]
。 然后,您要做的就是迭代初始char[][]
並將元素放置在新char[][]
中的適當位置。 所以在您的方法中,您會遇到類似
public void rotateBy90()
{
// bla bla
char[][] tempShape = new char[width][height];
for(int j = 0; j < width; j++) {
for(int i = 0; i < height; i++) {
tempShape[...][...] = myShape[i][j]; //I'll leave this as exercise
}
}
myShape = tempShape;
}
請注意:小心使用琴弦。 許多字符串操作涉及創建其他字符串( split
, substring
,concatenation等)。 如果長時間執行它們,則可能會很快耗盡內存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.