zoukankan      html  css  js  c++  java
  • leetcode 5 查找最长的回文子串

    给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。

    示例 1:

    输入: "babad"
    输出: "bab"
    注意: "aba" 也是一个有效答案。
    

    示例 2:

    输入: "cbbd"
    输出: "bb"

    public static  string LongestPalindrome(string s)
            {
                string result = "";
                if(string.IsNullOrWhiteSpace(s))
                {
                    return s;
                }
    
                if(s.Length == 1 || s.Length > 1000)
                {
                    return s;
                }
    
                else if(s.Length == 2)
                {
                    if(IsHuiZiChuan(s))
                    {
                        return s;
                    }
                    else
                    {
                        return s[0].ToString();
                    }
                }
    
                List<string> listTmp = new List<string>();
                int maxCount = 0;
                for(int i=0;i<s.Length -1;i++)
                {
                    string si = s[i].ToString();
                    for (int j=i+1;j<s.Length;j++)
                    {
                        si += s[j];
                        if(IsHuiZiChuan(si))
                        {
                            listTmp.Add(si);
                            if(si.Length > maxCount)
                            {
                                maxCount = si.Length;
                                result = si;
                            }
                        }
                        else
                        {
                            continue;
                        }
                    }
                }
                if(result == "")
                {
                    return s[0].ToString();
                }
    
                 
                
                return result;
            }
    
            public static bool IsHuiZiChuan(string str)
            {
                if(str.Length == 1)
                {
                    return true;
                }
    
                for (int i = 0; i < (str.Length / 2); i++)
                {
                    if(str[i] != str[str.Length - i -1])
                    {
                        return false;
                    }
    
                }
                return true;
    
               
            }

    代码可以执行,但是时间和空间复杂度不佳,还需要进一步优化。

  • 相关阅读:
    Topshelf 搭建 Windows 服务
    Xamarin.Android 6.0以后开启权限方法
    使用ADB安装apk安装包
    C# 杀掉系统中的进程
    C# 使用CefSharp嵌入网站
    .Net Core 基于 SnmpSharpNet 开发
    C#实现ActiveMQ消息队列
    ActiveMQ 安装方法
    C# FluentFTP类上传下载文件
    .NET Core 之 Nancy 基本使用
  • 原文地址:https://www.cnblogs.com/wangyu19900123/p/10449300.html
Copyright © 2011-2022 走看看