nsstring *str1 = @"qwe不重要我愛你的人的文字ty";
nsstring *str2 = @"哈qwe這也我愛你的人是ty";
nsarray *arr = [selfmatchlongestsubstrings:str1 with:str2];
nslog(@"最長的字串:%@", arr);
-(nsarray *)matchlongestsubstrings:(nsstring *)str1 with:(nsstring *)str2 {
// 所有重複的字串
nsarray*matchingstrarr = [nsarray array];
for(nsuinteger i = 0; i < str1.length; i++) {
unichar c = [str1 characteratindex:i];
nsstring *s = [nsstring stringwithformat:@"%c", c];
matchingstrarr = [matchingstrarr arraybyaddingobjectsfromarray:[selfcomparestr1:str1 tostr2:str2 withcharacterstring:s indexinstr1:i]];
// 去掉重複的資料
nsset*matchingstrset = [nsset setwitharray:matchingstrarr];
matchingstrarr = [matchingstrset allobjects];
// 陣列內字串按length降序排列
matchingstrarr = [matchingstrarr sortedarrayusingcomparator:^nscomparisonresult(id_nonnullobj1,id_nonnullobj2) {
return((nsstring*)obj1).length<((nsstring*)obj2).length;
nsinteger longestlength = matchingstrarr.firstobject.length;
__blocknsarray *longeststrarr = [nsarray array];
[matchingstrarr enumerateobjectsusingblock:^(nsstring *_nonnullobj, nsuinteger idx,bool*_nonnullstop) {
if(obj.length == longestlength) {
longeststrarr = [longeststrarr arraybyaddingobject:obj];
else{
*stop =yes;
returnlongeststrarr;
-(nsarray *)comparestr1:(nsstring *)str1 tostr2:(nsstring *)str2 withcharacterstring:(nsstring *)s indexinstr1:(nsuinteger)i{
if(![str2 containsstring:s]){
returnnil;
nsrange rangeofstr2 = [str2 rangeofstring:s];
nsmutablearray *longeststrarr = [nsmutablearray array];
for(nsuinteger j = rangeofstr2.location, ii = i; j < str2.length && ii < str1.length; j++, ii++) {
if([[str1 substringwithrange:nsmakerange(ii, 1)] isequaltostring:[str2 substringwithrange:nsmakerange(j, 1)]] ) {
if(j == str2.length - 1 || ii == str1.length - 1) {//匹配到字串最後乙個字元
nsstring *samestr = [str1 substringwithrange:nsmakerange(i, ii+1 - i)];
[longeststrarr addobject:samestr];
else{
nsstring *samestr = [str1 substringwithrange:nsmakerange(i, ii - i)];
[longeststrarr addobject:samestr];
break;
if(str2.length <=1) {
returnnil;// str2只剩1個字元,結束遞迴呼叫
str2 = [str2 substringfromindex:1];
if(str2.length>1) {
[longeststrarr addobjectsfromarray:[selfcomparestr1:str1 tostr2:str2 withcharacterstring:s indexinstr1:i]];
returnlongeststrarr;
查詢兩個字串中相同字元
for 歷遍第乙個字串的字元,過程中用 in 檢測字元是否存在於第二個字串中。若是在則將其新增在列表中。一 函式檔案 def intersect seq1,seq2 定義交集函式,函式名及變數 res 定義空列表用來盛放相同字元 for x in seq1 歷遍字串1 if x in seq2 歷遍...
判斷兩個字串是否相同
data segment mess1 db computer software mess2 db computer software data ends code segment assume ds data,cs code start mov ax,data mov ds,ax mov es,ax...
獲取兩個字串中相同的子串
package day15 author qitm date 2020 5 15 21 51 描述 獲取兩個字串中相同的子串 思路 1.既然取得最大子串,先看短的那個字串是否在長的字串中 如果存在,短的那個字串就是最大字串 2.如果不是,那麼就將短的字串進行長度遞減的方式減去子串,去長串中判斷是否存...