zoukankan      html  css  js  c++  java
  • leetcode 第五题 Longest Palindromic Substring (java)

    Longest Palindromic Substring

    Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

    time=255ms    accepted 暴力遍历

    public String longestPalindrome(String s){
            String result=null;
            int length=s.length();
            int max=0;
            if(length==0)
                return null;
            else if(length==1)
                return s;
            else{
                for(int i=1;i<length;i++){       
                    boolean b=false;
                    int k=0;
                    int j=0;
                    for(int m=i-1;m>=0&&m>=i-2;m--){
    	                if(s.charAt(i)==s.charAt(m)){
    	                    k=m-1;
    	                    b=true;
    	                    j=i+1;
    	                    while(b&&k>=0&&j<length){                    	
    	                        if(s.charAt(j)==s.charAt(k)){
    	                            j++;
    	                            k--;
    	                        }else
    	                            b=false;
    	                    }	                   
    	                    if(max<j-k-1){
    	                        result=s.substring(k+1,j);
    	                        max=j-k-1;
    	                    }
    	                }
                    }
                    if(j>=length)
                    	break;
                }
                return result;
            }
            
        }



  • 相关阅读:
    C语言实现大数计算
    shell编程题(九)
    shell编程题(八)
    信号(一)
    shell编程题(六)
    C语言实现webServer
    chrome导入导出常用书签
    JdbcTemplate
    数据库连接池
    JDBC
  • 原文地址:https://www.cnblogs.com/wennian/p/5036918.html
Copyright © 2011-2022 走看看