public class Solution {
private char[][] table = new char[][]{{'t', 'h', 'i', 's'}, {'w', 'a', 't', 's'}, {'o', 'a', 'h', 'g'}, {'f', 'g', 'd', 't'}};
private ArrayList<String> words = new ArrayList<>(4);
private ArrayList<Integer> hashs = new ArrayList<>(4);
public List<Vector> getMatchedWords() {
initWords();
initHashs();
LinkedList<Vector> result = new LinkedList<>();
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[0].length; j++) {
computeResult(i, j, result);
}
}
return result;
}
private void initWords() {
words.add("this");
words.add("two");
words.add("fat");
words.add("that");
}
private void initHashs() {
words.forEach(word -> hashs.add(word.hashCode()));
}
private void computeResult(final int i, final int j, LinkedList<Vector> result) {
Direction[] directions = Direction.values();
for (int m = 0; m < directions.length; m++) {
switch (directions[m]) {
case UP:
getLinearResult(i, -1, j, 0, result);
break;
case UPLEFT:
getLinearResult(i, -1, j, -1, result);
break;
case LEFT:
getLinearResult(i, 0, j, -1, result);
break;
case LEFTDOWN:
getLinearResult(i, 1, j, -1, result);
break;
case DOWN:
getLinearResult(i, 1, j, 0, result);
break;
case RIGHTDOWN:
getLinearResult(i, 1, j, 1, result);
break;
case RIGHT:
getLinearResult(i, 0, j, 1, result);
break;
case UPRIGHT:
getLinearResult(i, -1, j, 1, result);
break;
default:
}
}
}
private void getLinearResult(final int i, final int yOffset, final int j, final int xOffset, LinkedList<Vector> result) {
int iEnd = i; // 记录终点的横坐标
int jEnd = j; // 记录终点的纵坐标
String wordTmp = "";
while (iEnd >= 0 && jEnd >= 0 && iEnd < table.length && jEnd < table[0].length) {
wordTmp += table[iEnd][jEnd];
if (isHashCodeExist(wordTmp.hashCode()) && words.contains(wordTmp)) {
Vector vector = new Vector(i, j, iEnd, jEnd);
result.add(vector);
}
iEnd += yOffset;
jEnd += xOffset;
}
}
private boolean isHashCodeExist(int hash) {
return hashs.contains(hash);
}
private enum Direction {
UP(1), UPLEFT(2), LEFT(3), LEFTDOWN(4), DOWN(5), RIGHTDOWN(6), RIGHT(7), UPRIGHT(8);
private int code;
Direction(int code) {
this.code = code;
}
public int code() {
return code;
}
public static Direction resolve(Integer code) {
if (null == code) {
return null;
}
switch (code) {
case 1:
return UP;
case 2:
return UPLEFT;
case 3:
return LEFT;
case 4:
return LEFTDOWN;
case 5:
return DOWN;
case 6:
return RIGHTDOWN;
case 7:
return RIGHT;
case 8:
return UPRIGHT;
default:
return null;
}
}
}
protected class Vector {
private int stX;
private int stY;
private int enX;
private int enY;
public Vector(int sX, int sY, int eX, int eY) {
stX = sX;
stY = sY;
enX = eX;
enY = eY;
}
@Override
public String toString() {
return "坐标点为:(" + stX + "," + stY + ")->(" + enX + "," + enY + ")";
}
}
}
|