爪哇东西向和西向东发现者

时间:2011-12-08 09:55:30

标签: java

此代码可以找到一个单词,如果它从LEFT变为RIGHT,如何更改它以从右到左和从上到下查找单词?

boolean findWE(String word) {
  for (int r = 0; r < height; r++) {
    for (int c = 0; c <= width - word.length(); c++) {
      if (word.charAt(0) == grid[r][c]) {
        boolean failed = false;
        for (int i = 0; i < word.length() && !failed; i++) {
          if (word.charAt(i) != grid[r][c + i]) {
            failed = true;
          }
        }
        if (!failed) {
          System.out.printf("%s found WE at(%d,%d)\n", word, r, c);
          return true;
        }
      }
    }
  }
  return false;
}

1 个答案:

答案 0 :(得分:1)

由于这不是作业,您应该只能使用库函数来反转字符串:

boolean findEW(String word) {
  StringBuilder builder = new StringBuilder();

  // Why are your strings stored as a 2-dimensional character array??
  for(int r = 0; r < height; r++) {
    builder.append(grid[r]);
    builder.append("\n");
  }

  builder.reverse();
  return builder.toString().contains(word);
}

或者,由于在“edcba”中向后查找“abc”与在“edcba”中找到“cba”相同,您可以执行以下操作:

boolean findEW(String word) {
  return findWE(new StringBuilder(word).reverse());
}