華為OJ: 公用字串計算,華為oj
有幾個需要注意的地方,一個這道題是不區分大小寫,所以在計算之前對輸入的字串要做小寫或者大寫的轉換。
第二個,思路一定要清晰,先將s1從[i]處開始與s2的[j]開始匹配,不相等則j++直到j等於s2.length()-1,相等,則i++,j++。注意,這裡就是i++,即下次重新開始從s[i]開始匹配時,兩次i之間的距離可能會超過1。再j那裡設定一個計數器計數即可。
import java.util.Scanner;public class findMaxSubStringLength {public static int getCommonStrLength(String s1,String s2){int count=0;if(s1==" "||s2==" ")return 0;for(int i=0;i<s1.length();i++){for(int j=0;j<s2.length();j++){int number=0;if(i==s1.length()||j==s2.length()){break;}while(s1.charAt(i)==s2.charAt(j)){i++;j++;number++;count=count>number?count:number;if(i==s1.length()||j==s2.length()){break;}if(count==s1.length()||count==s2.length())return count;}}}return count;}public static void main(String args[]){Scanner input=new Scanner(System.in);String s1=input.next();String s2=input.next();s1=s1.toLowerCase();s2=s2.toLowerCase();System.out.println(getCommonStrLength(s1,s2));}}
求兩個字串最大公用子串問題已改看注釋
#include<stdio.h>
#include<malloc.h>
#include<string.h>
#include<stdlib.h>
#define MaxSize 100
typedef struct
{
char str[MaxSize] ;
int len ;
}SeqString ;
int SubSeqString( SeqString *Sub , SeqString S , int pos , int len )
{
int i ;
if( pos < 0 || pos > S.len || len > S.len - pos || len < 1 )
{
Sub -> len = 0 ;
return 0 ;
}
else
{
for( i = 0 ; i < len ; i ++ )
{
Sub -> str[i] = S.str[i+pos] ;
}
Sub->str[i] = '\0'; // 字串結束
Sub -> len = len ;
return 1 ;
}
}
int MaxSameSeqString( SeqString S , SeqString T , SeqString *M )
{
int i , j , k , t , pos ;
int len = 0 , maxlen = 0 ;
for( i = 0 ; i < S.len ; i++ )
{
k = i ;
for( j = 0 ; j < T.len ; j++ )
{
t = j ;
len = 0; // len賦值0
if( S.str[i] == T.str[j] )
{
while( S.str[k++] == T.str[t++] )
len++ ;
if( maxlen < len )
{
maxlen = len ;
pos = i ;
}
}
}
}
if( maxlen >= 1 )
{
SubSeqString( M , S , pos , maxlen ) ; // 參數maxlenlen
return 1 ;
}
return 0 ;
}
int main()
{
SeqString X , Y ;
SeqString *R = (SeqString*)malloc(sizeof (SeqString));
char a[MaxSize] , b[MaxSize] ;
scanf( "%s" , a ) ;
scanf( "%s" , b ) ;
int alen , blen ;
alen = strlen(a) ;
blen = strlen(b) ;
X.len = alen ;
Y.len = blen ;
strcpy( X.str , a ) ;
strcpy( Y.str , b ) ;
MaxSameSeqString( X , Y , R ) ;
printf("%s" , R -> str );
return 0 ;}
怎麼樣求兩個字串的最大公用子串?百度大公用子串
裡說要說多頭來還要去複製人家反正動態規划算法