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);
    	}
    }
    
  • 相关阅读:
    linux 文件记录锁详解
    Linux fcntl函数详解
    大数相加
    信雅达面试题atoi函数实现
    linux getopt函数详解
    strcpy和memcpy的区别
    手把手写数据结构之栈操作
    手把手写数据结构之队列操作
    手把手写数据结构之双向链表操作
    ORACLE查询内存溢出
  • 原文地址:https://www.cnblogs.com/zihaowang/p/4455806.html
Copyright © 2011-2022 走看看