面试题 01.05. 一次编辑

2022-12-12  本文已影响0人  spark打酱油

1.题目

字符串有三种编辑操作:插入一个英文字符、删除一个英文字符或者替换一个英文字符。 给定两个字符串,编写一个函数判定它们是否只需要一次(或者零次)编辑。
例子:oneEditAway("teacher","treacher")

2.思路

2.1 方法

双指针模拟

2.2 过程

3.代码

def oneEditAway(first: String, second: String): Boolean = {
    val firstLen: Int = first.length
    val secondLen: Int = second.length
    if(Math.abs(firstLen-secondLen)>1) return false
    if(firstLen<secondLen) return oneEditAway(second,first)
    var index1 = 0
    var index2 = 0
    var count = 0
    while (index1<firstLen&&index2<secondLen&&count<=1){
      val firstChar: Char = first(index1)
      val secondChar: Char = second(index2)
      if(firstChar==secondChar){
        index1=index1+1
        index2=index2+1
      }
      else {
        if(firstLen==secondLen){
          index1=index1+1
          index2=index2+1
          count=count+1
        }
        else {
          index1=index1+1
          count=count+1
        }
      }
    }
   return count<=1
  }

```            -    
上一篇下一篇

猜你喜欢

热点阅读