找到阵列中最长的扁平子部分?

时间:2012-11-19 09:49:29

标签: algorithm

有人可以告诉我最长的扁平部分是什么?

1 个答案:

答案 0 :(得分:2)

  

给定阵列a [0:n)(n≥0),如果∀i,则其子部分a [p,q)(0≤p≤q≤n)被称为“平坦”,j:p≤i≤ Ĵ

转换为英语,因为“当且仅当序列中的所有元素彼此相等时,子序列才被认为是平坦的”。由于平等是可传递的,反身的和对称的,你可以找到它:

pre: a is a sequence of symbols
     n is its length

last = null
bestAt = null
bestLen = -1
for each i in 0..n-1
  if a[i] != last
    thisAt = i
    thisLen = 1
    last=a[i]
    if thisLen > bestLen
      bestLen = thisLen
      bestAt = thisAt
  else
    thisLen++
  last=a[i]

post: a is not modified
      n is not modified
      bestAt holds the position of the first longest subsequence
      bestLen holds the length of the first longest subsequence