stringbuilder Scala 删除重复的字符

stringbuilder Scala drop duplicate chars

  class Buffer(s: String) {

  import scala.collection.mutable.StringBuilder
  import scala.io.StdIn

  private var buffer: StringBuilder = new StringBuilder(s)
  private var cursor: Int = 0  // cursor is in between characters
  private var marker: Int = 0  // marker is in between characters
  private var paste: String = ""
  private def end: Int = buffer.length              // the end of the line
  private def lwr: Int = Math.min(marker, cursor)
  private def upr: Int = Math.max(marker, cursor)

  /*
   * Accessor methods to return aspects of the state
   */
  def getCursor: Int = cursor
  def getMarker: Int = marker
  def getString: String = buffer.toString
  def getPaste: String = paste


          /**
       * Delete Duplicate characters.  Within the defined region, for each character,
       * if it occurs once then keep it, but if it occurs multiple times then keep
       * only the first occurrence.  The characters to the left and right of the
       * defined region remain unchanged, but within the defined region the duplicates
       * are removed. This operation does not affect the paste buffer. The cursor is
       * placed finally at the lower end of the defined region and the marker is placed
       * finally at the upper end of the (probably reduced) defined region. For example:
       * 
       *     m i s s i s s i p p i       marker =  1       
       *      ^                 ^        cursor = 10
       *
       * Then perform  sc('a', 'X')
       * 
       *     m i s p i      marker = 1       
       *      ^     ^       cursor = 4
       */
      def dd() 
      {
        var droppedchars: Int = 0;
         for (x <- lwr until upr)
         {
           var c = buffer.charAt(x)
           for (i <- lwr until upr)
           {
             if (buffer.charAt(i) == c)
             {
               buffer.deleteCharAt(i)
               droppedchars += 1

             }
           }
           marker = lwr
           cursor = upr - droppedchars


         }
      }

在这方面也需要一些帮助,但似乎没有用 函数需要删除它找到的任何重复字符,将标记移回新定义区域的开头,将光标移到新定义区域的末尾,不要求有人为我写这个只是指导我朝着正确的方向前进

您尝试执行的操作需要 O(n^2),从性能角度来看这不是很好... Imo,一个更好的解决方案是在缓冲区上只使用一个循环,并且在缓冲区中每个字符 c 你应该检查一组字符(在 for 循环外声明):

val  chars = scala.collection.mutable.Set[Char]()

...

for (x <- lwr until upr) {
  var c = buffer.charAt(x)
  if (chars contains c) buffer.deleteCharAt(x) else chars += c
}
cursor = marker + chars.size

为什么不只是:

scala> "mississippi".distinct
res22: String = misp