zoukankan      html  css  js  c++  java
  • Java [leetcode 5] 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.

    解题思路:

    遍历方法,时间复杂度为O(n)。首先从字符串的开头位置一直往后遍历,在每次遍历的过程中由该位置向两边扩散,直到找到最长的子回文串为止。同时需要考虑奇字符串和偶字符串的情况。

    代码如下:

    public class Solution {
       public String longestPalindrome(String s) {
    		int n = s.length();
    		String longest = s.substring(0, 1);
    
    		if (s == null || s.length() == 0)
    			return null;
    		for (int i = 0; i < n; i++) {
    			String p1 = expandFromCenter(s, i, i);
    			if (p1.length() > longest.length())
    				longest = p1;
    			String p2 = expandFromCenter(s, i, i + 1);
    			if (p2.length() > longest.length())
    				longest = p2;
    		}
    		return longest;
    	}
    
    	public String expandFromCenter(String s, int c1, int c2) {
    		int head = c1;
    		int tail = c2;
    		int m = s.length();
    
    		while (head >= 0 && tail < m && s.charAt(head) == s.charAt(tail)) {
    			head--;
    			tail++;
    		}
    		return s.substring(head + 1, tail);
    	}
    }
    
  • 相关阅读:
    python基础十一之装饰器进阶
    python基础十之装饰器
    python基础九之函数
    python基础八之文件操作
    python基础七之copy
    python基础七之集合
    python基础数据类型汇总
    python基础六之编码
    synchronized关键字的内存语义
    对于this和当前线程的一些理解
  • 原文地址:https://www.cnblogs.com/zihaowang/p/4455806.html
Copyright © 2011-2022 走看看