本人菜鸟一枚,今天刚刚开始刷 LeetCode 的算法题。打算从通过率最高的题开始刷,于是就选择了这一道: 把题目描述粘贴如下:
Given an 2D board, count how many different battleships are in it. The battleships are represented with 'X's, empty slots are represented with '.'s. You may assume the following rules:
1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size.Example:
X..X
...X
...X
In the above board there are 2 battleships.
Invalid Example:
...X
XXXX
...X
This is not a valid board - as battleships will always have a cell separating between them. Your algorithm should not modify the value of the board.
我一开始用了很多层 if 嵌套,大概写了 50 多行,通过了测试。后来转换思路,改进了一下程序,改进之后的代码如下:
def count_battleships(board)
  count = 0
  y = board[0].size
  str = ""
  board.each {|s| str << s.to_s}
  str.size.times do |i|
    if str[i] == "X" && (str[i+1] != "X" || (i+1)% y ==0)  && str[i + y] != "X"
      count += 1
    end
  end
  return count
end
puts count_battleships(["X..X","...X","...X"])
奇怪的事情就在这时发生了,LeetCode OJ 上得到的结果是错误的,但是我在本地跑没问题,更奇怪的是,在 LeetCode 上 stdout 结果也是正确的,但是返回的结果就会自动乘以 2,我试了几个测试都是这样。截图如下。

我现在完全懵逼了,不知道是哪儿的问题,请大神指点。。