본문 바로가기

Algorithms/11 Coding Interview (CS Dojo)

One Away Strings (Java)

Write a function that takes two strings and returns true if they are one away from each other.

They are one away from each other if a single operation (changing a character, deleting a character or adding a character) will change one of the strings to the other.

Examples:

  • "abcde" and "abcd" are one away (deleting a character).
  • "a" and "a" are one away (changing the only character 'a' to the equivalent character 'a').
  • "abc" and "bcc" are NOT one away. (They are two operations away.)


풀이


이전문제에 비해 생각이 좀 더 많이 필요했다.

문자비교 관련해서는 charAt을 잘 활용 하는것이 중요하다.

두개의 array 비교 관련 문제를 할 때 index로 하나씩 비교해가면 잘 풀리는 거 같다.


먼저 2개의 array 가 아예 equals 면 바로 true 주고

2개의 array length가 2개 이상이면 false를 준다. 


2개의 array length가 같을 경우 각각 index 별로 비교해보면서 다른 문자가 2개 이상이면 false 아니면 true


2개의 array length가 다를 경우, 더 큰 array의 index를 어떻게 옮길 지 고민해보면 풀린다.


package com.company;

public class Main {

public static void main(String[] args) {
// write your code here
isOneAway("abcde", "abcd"); // should return true
isOneAway("abde", "abcde"); // should return true
isOneAway("a", "a"); // should return true
isOneAway("abcdef", "abqdef"); // should return true
isOneAway("abcdef", "abccef"); // should return true
isOneAway("abcdef", "abcde"); // should return true
isOneAway("aaa", "abc"); // should return false
isOneAway("abcde", "abc"); // should return false
isOneAway("abc", "abcde"); // should return false
isOneAway("abc", "bcc"); // should return false

}

public static Boolean isOneAway(String s1, String s2) {
if (s1.equals(s2)) return true;
if (Math.abs(s1.length() - s2.length()) > 1) return false;
if (s1.length() == s2.length()) return isOneAwaySameLength(s1, s2);
if (s1.length() > s2.length()) return isOneAwayDifferentLength(s1, s2);
else return isOneAwayDifferentLength(s2, s1);
}

private static Boolean isOneAwaySameLength(String s1, String s2){
int diffCount = 0;
for (int i = 0; i < s1.length(); i++){
if (s1.charAt(i) != s2.charAt(i)){
diffCount ++;
if (diffCount > 1) return false;
}
}
return true;
}

private static Boolean isOneAwayDifferentLength(String s1, String s2){
int diffCount = 0;
int index = 0;
while (index < s1.length() -1){
if (s1.charAt(index + diffCount) != s2.charAt(index)) {
diffCount ++;
if (diffCount > 1) return false;
}
else index++;
}
return true;
}
}