最长回文子串
给你一个字符串 s
,找到 s
中最长的回文子串。
注意,空串的创建方法是string xx="";
C#中可以使用+来串联字符串;
public class Solution {
public string LongestPalindrome(string s) {
string str="";
bool ishw;
for(int i=0;i<s.Length-1;i++)
{
for(int j=s.Length-1;j>i;j--)
{
if(j-i+1<=str.Length)
break;
ishw=true;
if(s[i]==s[j])
{
for(int k=1;k<=(j-i)/2;k++)
if(s[i+k]!=s[j-k])
{
ishw=false;
break;
}
if(ishw&&j-i+1>str.Length)
{
str="";
for(int k=i;k<=j;k++)
str+=s[k];
}
}
}
}
if(str.Length==0)
str+=s[0];
return str;
}
}
翻转字符串里的单词
C#中字符串类有以下两个方法,注意假如有字符串x+y,用remove移除y,返回的是x
public class Solution {
public string ReverseWords(string s) {
string news="";
int i;
while(s.Length!=0)
{
i=1;
while(s.Length!=0&&s[s.Length-1]==' ')
s=s.Remove(s.Length-1);
while(i<=s.Length&&s[s.Length-i]!=' ')
i++;
if(i>1)
{
for(int j=0;j<i-1;j++)
news+=s[s.Length-i+1+j];
s=s.Remove(s.Length-i+1);
news+=" ";
}
}
news=news.Remove(news.Length-1);
return news;
}
}
字符串匹配
字符串匹配是有一个高效的KMP算法,这里先不赘述。
在不使用KMP算法的情况下,要么遍历长串,要么直接使用C#的函数。