Saturday, September 2, 2017

LeetCode - 5. Longest Palindromic Substring

Source Link:
https://leetcode.com/problems/longest-palindromic-substring/description/

Question:
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example:
Input: "babad"
Output: "bab" 
Note: "aba" is also a valid answer.

My Solution: Note:
1. main idea: Expand Around Center
a palindrome can be "expanded" from its center
2. we need to keep "the max length" and "the start point of the max palindrome"
int max_len = 0;
int max_start =0;
3. try to expand the palindrome from the "center"
for(int i=0; i < s.length(); i++){
expand(s, i, i); // case 1: the Palindrome is with "odd" length
expand(s, i, i+1); // case 2: the Palindrome is with "even" length
 
4. the longest palindrome by using str.substring(int start, int end)
longest_palindrome = s.substring(max_start, max_start + max_len); 
5. write a function to expand the palindrome from the "center"
public void expand(String s, int left, int right)
6. while s.charAt(left)==s.charAt(right), then expand by "left--" and "right++"
while(left >=0 && right <= s.length()-1 && s.charAt(left) == s.charAt(right)){
left --;
right ++;
}
7. note: we ill do "left--" and "right++" one more time
the current start and end points are "left+1" and "right-1" (be careful)

int cur_start = left +1;
int cur_end = right - 1;

No comments:

Post a Comment

Codility - Lesson 16 Greedy algorithms - 2. MaxNonoverlappingSegments

Source Link: https://app.codility.com/programmers/lessons/16-greedy_algorithms/max_nonoverlapping_segments/ Question: Located on a line ...