Created
August 30, 2019 10:28
-
-
Save yydai/32da1c8cfade353c8ae26950483bf40b to your computer and use it in GitHub Desktop.
adjacent single char exchange
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.apache.hadoop.hive.ql.exec.UDF; | |
public class CheckSwapCharsUDF extends UDF { | |
public Integer evaluate(String str1, String str2) throws Exception { | |
if (str1 == null || str2 == null) | |
return -1; | |
int s1_len = str1.length(); | |
int s2_len = str2.length(); | |
if (s1_len != s2_len) | |
return -1; | |
return check(str1, str2, s1_len, s2_len); | |
} | |
/** | |
* 判断两个长度相同的串,是否仅仅有两个相邻字符交换 | |
* 例如: "天安门" 和 "安天门" | |
*/ | |
public static int check(String str1, String str2, int s1_len, int s2_len) { | |
if (s1_len != s2_len) | |
return -1; | |
int flag = 0; | |
int i = 0, j =0; | |
while (i < s1_len && j < s2_len) { | |
if (str1.charAt(i) == str2.charAt(j)) { | |
i ++; | |
j ++; | |
} else { | |
if (flag == 1 || i + 1 >= s1_len || j + 1 >= s2_len) | |
return -1; | |
if (str2.charAt(j) == str1.charAt(i+1) && str2.charAt(j+1) == str1.charAt(i)) { | |
i += 2; | |
j += 2; | |
flag = 1; | |
} else | |
return -1; | |
} | |
} | |
return 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment