这是一个有趣的问题需要解决。
嵌套循环很容易让人陷入困境。
我注意到,如果我把单词组合成一个字符串,就会出现一种模式。
以原帖为例,将三个单词“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个字母组成的单词。
对角线单词的数量为字母数+单词数-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) {
}
if (direction == UP_RIGHT) {
}
if (direction == UP_LEFT) {
}
}
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();
}
}