最长不连续子串

import java.util.HashMap;  
import java.util.Map;  
public class zuichang {  
    public static void main(String[] args) {  
        longestNodupSubstring("1201354351");  
    }  
    /**cursor里面存放字符的在字符串中的位置 
     * lengAt[i]存放以字符string.charAt(i)结尾的最长子字符串的长度 
     * @param string 
     */  
    public static void longestNodupSubstring(String string)  
    {  
        int len = string.length();//字符串长度  
        if(len>0){  
            Map<Character,Integer> cursor = new HashMap<Character,Integer>();  
            cursor.put(string.charAt(0), 0); //将字符串中首字母添加到map中去 
            int [] lengthAt = new int[string.length()];// 声明一个数组存放最长字符串的长度
            lengthAt[0] =1;  //此时map字符中对应的长度是
            int max =0;  
            for(int i = 1 ;i<len;i++){  
                char c = string.charAt(i);  
                if(cursor.containsKey(c)){  
                    lengthAt[i] = Math.min(lengthAt[i-1]+1, i-cursor.get(c));     
                }else {  
                    lengthAt[i] = lengthAt[i-1]+1;  
                }  
                max = Math.max(max, lengthAt[i]);  
                cursor.put(c, i);  
            }  
            for(int i=0;i<len;i++){  
                if(max == lengthAt[i]){  
                    System.out.println(string.substring(i-max+1, i+1));  
                }  
            }  
        }  
    }  
  
}  
在C语言中,找到两个字符串的最长公共连续子串(Longest Common Substring)可以通过动态规划的方法来实现。动态规划是一种将复杂问题分解为更简单的子问题,并通过存储子问题的结果来避免重复计算的算法设计方法。 以下是一个实现最长公共连续子串的C语言代码示例: ```c #include <stdio.h> #include <string.h> // 函数声明 int longestCommonSubstring(char *str1, char *str2, char *lcs); int main() { char str1[100], str2[100], lcs[100]; printf("请输入第一个字符串: "); scanf("%s", str1); printf("请输入第二个字符串: "); scanf("%s", str2); int len = longestCommonSubstring(str1, str2, lcs); if (len > 0) { printf("最长公共连续子串是: %s\n", lcs); printf("长度是: %d\n", len); } else { printf("没有公共连续子串\n"); } return 0; } int longestCommonSubstring(char *str1, char *str2, char *lcs) { int len1 = strlen(str1); int len2 = strlen(str2); int maxLen = 0, endIndex = 0; // 创建一个二维数组来存储子问题的结果 int dp[len1][len2]; memset(dp, 0, sizeof(dp)); // 填充dp数组 for (int i = 0; i < len1; i++) { for (int j = 0; j < len2; j++) { if (str1[i] == str2[j]) { if (i == 0 || j == 0) { dp[i][j] = 1; } else { dp[i][j] = dp[i - 1][j - 1] + 1; } if (dp[i][j] > maxLen) { maxLen = dp[i][j]; endIndex = i; } } else { dp[i][j] = 0; } } } // 提取最长公共连续子串 if (maxLen > 0) { int index = endIndex - maxLen + 1; for (int i = index; i <= endIndex; i++) { lcs[i - index] = str1[i]; } lcs[maxLen] = '\0'; } return maxLen; } ``` 这个程序首先从用户那里获取两个字符串,然后调用`longestCommonSubstring`函数来计算它们的最长公共连续子串。该函数使用动态规划的方法,通过一个二维数组`dp`来存储子问题的结果,并最终返回最长公共连续子串的长度和子串本身。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值