字符串处理

2个字符串a,b,

 A:abcdefghi       B:abcgi 返回true

A:abcdefghi       B:abz     返回false(因为字符串A不包含字母Z)

任意语言,但是注意要最优算法,另外,也要处理异常状况。你输入的有可能是乱码,有可能A比B字符串还短,也有可能空字符串,还有如果字符串不是排序而是乱序。

//假设str1和str2不是排序的,时间复杂度 str1.Length*str2.Length

staticbool M2(string str1, string str2)

{

 

 

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

{

 

 

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;

}

posted @ 2013-12-27 10:29  purplesun  阅读(152)  评论(0编辑  收藏  举报