题目:
1、判断一个字符串是否为回文
2、判断一个字符串是否包含回文(至少三个字符)
3、求一个字符串中最长的回文
4、判断一个字符串中某个字符串出现的次数
算法:
1、判断一个字符串是否为回文
解决思路:定义一个空字符串,让它等于判断字符串的倒序,比较两者是否相等,如果相等,是回文,不相等,不是回文
1 public static bool IsHuiWen(string str) 2 { 3 //判断字符串是否小于3,如果小于,则不需要判断 4 if (str.Length < 3) 5 { 6 return false; 7 } 8 else 9 { 10 string str2 = ""; 11 for(int i = str.Length - 1; i >= 0; i--) 12 { 13 str2 += str[i]; 14 } 15 if (str == str2) 16 { 17 return true; 18 } 19 else 20 { 21 return false; 22 } 23 } 24 }
2、判断一个字符串是否包含回文(至少三个字符)
解决思路:遍历每个子串,需要用到SubString截取字符串,并判断是否为回文
public static bool IsContainHuiWen(string str) { int startIndex = 0;//开始遍历的索引 int Count = 3; //每次至少遍历的长度 while (true) { string child = str.Substring(startIndex, Count);//截取一个子串,判断子串是否为回文 bool b = IsHuiWen(child); if (b == false) { Count++; if (startIndex + Count > str.Length) { startIndex++; Count = 3; if (startIndex > str.Length - Count) { break; } } } else { return true; } } return false; }
3、求一个字符串中最长的回文
解决思路:再前两题的基础上,修改判断条件,定义res变量,保存每次查找到的最大回文
ps:判断条件要和继续判断分开,否则会死循环
public static string MaxHuiWen(string str) { int startIndex = 0;//开始遍历的索引 int Count = 3; //每次至少遍历的长度 string res = ""; while (true) { string child = str.Substring(startIndex, Count);//截取一个子串,判断子串是否为回文 bool b = IsHuiWen(child); if (b) { if (res.Length < child.Length) { res = child; } } //继续判断 Count++; if (startIndex + Count > str.Length) { startIndex++; Count = 3; if (startIndex > str.Length - Count) { break; } } } return res; }
4、判断一个字符串中某个字符串出现的次数
解决思路:通过IndexOf方法找到每次字符串出现的下标,并通过SubStr方法截取源字符串的的长度,定义一个num保存出现的次数
ps:每次截取的时候,index+1,否则会死循环
public static int GetStrNum(string str,string child) { int num = 0; int index = 0; while (true) { index = str.IndexOf(child); if (index == -1) { return num; } else { num++; str = str.Substring(index+1); Console.WriteLine(str); } } }
ps:第一次写博客,写完了网断了,重连后也不能保存,只好重写了一遍。。。
原文:https://www.cnblogs.com/smaleeel/p/12263090.html