1.计算字符串的编辑距离
Levenshtein 距离,又称编辑距离,指的是两个字符串之间,由一个转换成另一个所需的最少编辑操作次数。许可的编辑操作包括将一个字符替换成另一个字符,插入一个字符,删除一个字符。编辑距离的算法是首先由俄国科学家 Levenshtein 提出的,故又叫 Levenshtein Distance 。
例如:
字符串A: abcdefg
字符串B: abcdef
通过增加或是删掉字符 ”g” 的方式达到目的。这两种方案都需要一次操作。把这个操作所需要的次数定义为两个字符串的距离。
要求:
给定任意两个字符串,写出一个算法计算它们的编辑距离。
数据范围:给定的字符串长度满足 1 \le len(str) \le 1000 \1≤len(str)≤1000
输入描述:
每组用例一共2行,为输入的两个字符串
输出描述:
每组用例输出一行,代表字符串的距离
示例1
输入:
abcdefg abcdef输出:
1
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sca = new Scanner(System.in);
while(sca.hasNext()){
String str1 = sca.nextLine();
String str2 = sca.nextLine();
System.out.println(getdistance(str1,str2));
}
}
public static int getdistance(String str1,String str2){
char[] wd1 = str1.toCharArray();
char[] wd2 = str2.toCharArray();
int len1 = wd1.length;
int len2 = wd2.length;
int[][] dist = new int[len1+1][len2+1];
//初始状态
for(int i = 0; i <= len1;i++){
dist[i][0] = i;
}
for(int j = 0;j <= len2;j++){
dist[0][j] = j;
}
for(int i = 1;i <= len1;i++){
for(int j = 1;j <= len2;j++){
//先求出插入和删除的最小值
dist[i][j] = Math.min(dist[i-1][j],dist[i][j-1])+1;
if(wd1[i-1] == wd2[j-1]){
//不需要替换
dist[i][j] = Math.min(dist[i][j],dist[i-1][j-1]);
}else{
dist[i][j] = Math.min(dist[i][j],dist[i-1][j-1]+1);
}
}
}
return dist[len1][len2];
}
}
2.微信红包
春节期间小明使用微信收到很多个红包,非常开心。在查看领取红包记录时发现,某个红包金额出现的次数超过了红包总数的一半。请帮小明找到该红包金额。写出具体算法思路和代码实现,要求算法尽可能高效。
给定一个红包的金额数组 gifts 及它的大小 n ,请返回所求红包的金额。
若没有金额超过总数的一半,返回0。
数据范围: 1 \le n \le 1000 \1≤n≤1000 ,红包金额满足 1 \le gift_i \le 100000\1≤gifti≤100000
示例1
输入:
[1,2,3,2,2],5返回值:
2示例2
输入:
[1,1,2,2,3,3],6返回值:
0
import java.util.*;
public class Gift {
public int getValue(int[] gifts, int n) {
HashMap<Integer,Integer> map = new HashMap<>();
for(int g : gifts){
if(map.containsKey(g)){
map.put(g,map.get(g)+1);
}else{
map.put(g,1);
}
if(map.get(g) > n /2){
return g;
}
}
return 0;
}
}