字符串處理

2個字符串a,b,算法

 A:abcdefghi       B:abcgi 返回truespa

A:abcdefghi       B:abz     返回false(由於字符串A不包含字母Z)排序

任意語言,可是注意要最優算法,另外,也要處理異常情況。你輸入的有多是亂碼,有可能A比B字符串還短,也有可能空字符串,還有若是字符串不是排序而是亂序。字符串

//假設str1和str2不是排序的,時間複雜度 str1.Length*str2.Lengthstring

staticbool M2(string str1, string str2)亂碼

{cgi

 

 

if (str1 == null || str2 == null || str2.Length == 0 || str1.Length == 0)異常

{static

 

 

returnfalse;語言

}

 

 

for (int i = 0; i < str2.Length; i++)

{

 

 

bool find = false;

for (int j = 0; j < str1.Length; j++)

{

 

 

if (str1[j] == str2[i])

{

find =

 

true;

break;

}

}

 

 

if (find == false)

{

 

 

returnfalse;

}

}

 

 

returntrue;

}

 

 

//假設str1和str2是排序的,時間複雜度 str1.Length+str2.Length

staticbool M(string str1, string str2)

{

 

 

if (str1 == null || str2 == null || str2.Length == 0 || str1.Length == 0)

{

 

 

returnfalse;

}

 

 

int j = 0;

int i = 0;

while (i < str2.Length)

{

 

 

while (j < str1.Length)

{

 

 

if (str2[i] == str1[j])

{

 

 

break;

}

j++;

}

 

 

if (j >= str1.Length)

{

 

 

break;

}

i++;

}

 

 

 

returnfalse;

}

相關文章
相關標籤/搜索