提取字符串最长子串

思路:

第1步:输入两个自定义的字符串

第2步:求出所有共同的子串

第3步:找到长度最长的子串


下面是scala编程版本的实现

import scala.collection.mutable


object longestSubstr {
  def allSubstr(str1:String, str2:String) :mutable.HashSet[String] = {
    val minLength = math.min(str1.length, str2.length)
    var rst = new mutable.HashSet[String]
    for(i <- 0 until str1.length){
      val startChar1 = str1.charAt(i)
      for(j <- 0 until str2.length){
        var pointer1 = i
        var pointer2 = 0
        if(str2.charAt(j).equals(startChar1)){
          var subString = ""
          subString += str2.charAt(j)
          pointer2 = j
          var flag = true
          while(flag){
            pointer1 += 1
            pointer2 += 1
            if(pointer1 < str1.length && pointer2 < str2.length && str1.charAt(pointer1).equals(str2.charAt(pointer2))){
              subString += str1.charAt(pointer1)
            }else{
              flag = false
            }
          }
          rst.add(subString)
        }
      }
    }
    rst
  }

  def main(args:Array[String]) ={
      val s1 = scala.io.StdIn.readLine()
      val s2 = scala.io.StdIn.readLine()
      val allSubString = allSubstr(s1,s2)
//      for(str <- allSubString) println(str)

      var rstSubStr = ""
      var maxValue = 0
      for(str <- allSubString){
        if (str.length >= maxValue) {
          rstSubStr = str
          maxValue = str.length
        }
      }
      println(s"The longest substring is $rstSubStr, its length is $maxValue")
  }
}


你可能感兴趣的:(scala)