这是一个有趣的问题。
很容易陷入嵌套循环。
我注意到如果我把这些词放在一个字符串中,就会出现一种模式。
以 OP 为例,“SUGAR”、“GLASS”、“MOUSE”这三个词连接在一起形成 SUGARGLASSMOUSE。
这是我需要从连接字符串中获取的字符的从零开始的字符位置。我已经把它们排成一行,这样你就可以更容易地看到图案。
10 M
5 11 GO
0 6 12 SLU
1 7 13 UAS
2 8 14 GSE
3 9 AS
4 R
看到图案了吗?我有 3 个索引,由 5 次迭代组成。我有 3 个单词,由 5 个字母组成。
对角词的数量是letters + words - 1
。我们减去 1,因为字符位置 0 的第一个字母只使用一次。
这是我运行的测试的结果。
[ "SUGAR" "GLASS" "MOUSE" "STATE" "PUPIL" "TESTS" ]
[ "T" "PE" "SUS" "MTPT" "GOAIS" "SLUTL" "UASE" "GSE" "AS" "R" ]
[ "SUGAR" "GLASS" "MOUSE" ]
[ "M" "GO" "SLU" "UAS" "GSE" "AS" "R" ]
这是代码:
import java.util.ArrayList;
import java.util.List;
public class Matrix {
public static final int DOWN_RIGHT = 1;
public static final int DOWN_LEFT = 2;
public static final int UP_RIGHT = 4;
public static final int UP_LEFT = 8;
public String[] getMatrixDiagonal(String[] grid, int direction) {
StringBuilder builder = new StringBuilder();
for (String s : grid) {
builder.append(s);
}
String matrixString = builder.toString();
int wordLength = grid[0].length();
int numberOfWords = grid.length;
List<String> list = new ArrayList<String>();
if (wordLength > 0) {
int[] indexes = new int[numberOfWords];
if (direction == DOWN_RIGHT) {
indexes[0] = matrixString.length() - wordLength;
for (int i = 1; i < numberOfWords; i++) {
indexes[i] = indexes[i - 1] - wordLength;
}
int wordCount = numberOfWords + wordLength - 1;
for (int i = 0; i < wordCount; i++) {
builder.delete(0, builder.length());
for (int j = 0; (j <= i) && (j < numberOfWords); j++) {
if (indexes[j] < wordLength * (wordCount - i)) {
char c = matrixString.charAt(indexes[j]);
builder.append(c);
indexes[j]++;
}
}
String s = builder.reverse().toString();
list.add(s);
}
}
if (direction == DOWN_LEFT) {
// Exercise for original poster
}
if (direction == UP_RIGHT) {
// Exercise for original poster
}
if (direction == UP_LEFT) {
// Exercise for original poster
// Same as DOWN_RIGHT with the reverse() removed
}
}
return list.toArray(new String[list.size()]);
}
public static void main(String[] args) {
String[] grid1 = { "SUGAR", "GLASS", "MOUSE", "STATE", "PUPIL", "TESTS" };
String[] grid2 = { "SUGAR", "GLASS", "MOUSE" };
Matrix matrix = new Matrix();
String[] output = matrix.getMatrixDiagonal(grid1, DOWN_RIGHT);
System.out.println(createStringLine(grid1));
System.out.println(createStringLine(output));
output = matrix.getMatrixDiagonal(grid2, DOWN_RIGHT);
System.out.println(createStringLine(grid2));
System.out.println(createStringLine(output));
}
private static String createStringLine(String[] values) {
StringBuilder builder = new StringBuilder();
builder.append("[ ");
for (String s : values) {
builder.append("\"");
builder.append(s);
builder.append("\" ");
}
builder.append("]");
return builder.toString();
}
}