目录
1.字符串计数
链接:字符串计数_美团笔试题_牛客网
来源:牛客网
[编程题]字符串计数
- 热度指数:11277 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
- 算法知识视频讲解
求字典序在 s1 和 s2 之间的,长度在 len1 到 len2 的字符串的个数,结果 mod 1000007。
输入描述:
每组数据包涵s1(长度小于50),s2(长度小于50),len1(小于50),len2(大于len1,小于50)
输出描述:
输出答案。示例1
输入
ab ce 1 2输出
56
- 全部代码
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
StringBuffer s1 = new StringBuffer(sc.next());
StringBuffer s2 = new StringBuffer(sc.next());
int len1 = sc.nextInt();
int len2 = sc.nextInt();
// 给s1后面补"a",s2后面补"z"
for(int i = s1.length();i < len2;i++){
s1.append('a');
}
for(int i = s2.length();i < len2;i++){
s2.append('z');
}
// 将s1和s2对应位置上的字符相减并保存相减的结果
int[] array = new int[len2];
for(int i = 0; i < len2; i++){
array[i] = s2.charAt(i) - s1.charAt(i);
}
// 计算结果
long result = 0;
for(int i = len1; i <= len2; i++){
for(int j = 0; j < i; j++){
result += array[j]*Math.pow(26, i - j - 1);
}
}
System.out.println((result-1)%1000007);
}
}
}
2.最长公共子序列
链接:最长公共子序列__牛客网
来源:牛客网
[编程题]最长公共子序列
- 热度指数:5773 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
- 算法知识视频讲解
我们有两个字符串m和n,如果它们的子串a和b内容相同,则称a和b是m和n的公共子序列。子串中的字符不一定在原字符串中连续。
例如字符串“abcfbc”和“abfcab”,其中“abc”同时出现在两个字符串中,因此“abc”是它们的公共子序列。此外,“ab”、“af”等都是它们的字串。
现在给你两个任意字符串(不包含空格),请帮忙计算它们的最长公共子序列的长度。输入描述:
输入包含多组数据。 每组数据包含两个字符串m和n,它们仅包含字母,并且长度不超过1024。
输出描述:
对应每组输入,输出最长公共子序列的长度。示例1
输入
abcfbc abfcab programming contest abcd mnp输出
4 2 0
- 全部代码
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String s1 = sc.next();
String s2 = sc.next();
int result = 0;
if(s1 == null || s2 == null){
System.out.println(result);
return;
}
int[][] dp = new int[s1.length()+1][s2.length()+1];
for (int i = 0;i <= s1.length();i++){
for (int j = 0;j <= s2.length();j++){
if(i == 0 || j == 0){
dp[i][j] = 0;
}else if(s1.charAt(i-1) == s2.charAt(j-1)){
dp[i][j] = dp[i-1][j-1] +1;
}else {
dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);
}
}
}
System.out.println(dp[s1.length()][s2.length()]);
}
}
}