1

我需要在 ruby​​ 中修改一个字符串。具体来说,我正在尝试从 WKT 字符串中删除“孔”。孔被定义为在第一个括号之后的任何一组括号,其中包含数字。例如在这个字符串中...... POLYGON ((1 2, 3 4), (5 6, 7 8))

我需要删除, (5 6, 7 8),因为这个括号数据是一个洞,逗号和空格不属于单独的括号组。

我正在避免使用 ruby​​ 方法,例如matchscan尝试优化速度并实现 O(n) 速度。

这是我到目前为止所拥有的。

def remove_holes_from(wkt)
    output_string = ""
    last_3_chars  = [ nil, nil, nil ]
    number_chars  = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ]

    should_delete_chars = false

    wkt.each_char do |char|
      last_3_chars.shift
      last_3_chars.push(char)
      if should_delete_chars == false
        if number_chars.include?(last_3_chars[0]) && last_3_chars[1] == ")" && last_3_chars[2] == ","
          should_delete_chars = true
          next
        else
          output_string += char
        end
      end

      if should_delete_chars == true
        if number_chars.include?(last_3_chars[0]) && last_3_chars[1] == ")" && last_3_chars[2] == ")"
          should_delete_chars = false
          output_string += char
        else
          next
        end
      end
    end
    output_string
  end

我面临的问题是,对于像美国这样的大型多边形(超过 500,000 个字符和超过 40,000 个点),我需要 66 秒才能完成此操作。你可以在这里找到字符串: https ://gist.github.com/cheeseandpepper/9da5ca6ade921da2b4ab

谁能想到我可以使用的这个例子的优化?或者也许是一种单独的方法?谢谢。

4

1 回答 1

2

Whelp...正则表达式获胜!

wkt.gsub(/, \(-?\d.*?\)/, "")

花了我 0.003742 秒

至于正则表达式

,文字逗号

文字空间

\(文字左括号

-?可选的负号

\d任何数字(因为前面是可选的,我们需要确保我们有一个数字与另一个左括号)

.*任意数量的任意字符(将是数字、逗号和负号)

?\)直到并包括一个文字右括号

于 2015-08-27T17:45:44.807 回答