Valid Palindrome
Last updated
Last updated
IsPalindrome LongestPalindrome as second variation which returns the longest palindrome in a given string or an array of strings if there are multiple of the same length.
2道找回文:2.1 在句子里忽略特殊符号大小写找回文;2.2在句子里找出所有同样长度且最长的回文, 按照原来的格式输出(保留特殊符号大小写)
class Solution {
public boolean isPalindrome(String s) {
s = s.toLowerCase();
int left = 0;
int right = s.length()-1;
while(left< right)
{
while(left < s.length() && !isValid(s.charAt(left)))
{
left++;
}
while(right > 0 && !isValid(s.charAt(right)))
{
right--;
}
if(left < right && s.charAt(left) != s.charAt(right) )
{
return false;
}
left++;
right--;
}
return true;
}
public boolean isValid(char c)
{
return Character.isLetter(c) || Character.isDigit(c);
}
}
Followup: similar as LC 5: Longest Palindromic Substring
return all longest palindrome in a string
public class AllPalindromeSubString {
public static void main(String[] args)
{
String input = "babad";
List<String> res = findAllSubString(input);
System.out.println(res);
}
public static List<String> findAllSubString(String s)
{
List<String> res = new ArrayList<>();
int maxCount = 0;
for(int i = 0; i< s.length()-1; i++)
{
String s1 = getPalindromesubstring(s, i, i);
String s2 = getPalindromesubstring(s, i, i+1);
maxCount = Math.max(maxCount, Math.max(s1.length(), s2.length()));
if(s1.length() == maxCount)
{
res.add(s1);
}
if(s2.length() == maxCount)
{
res.add(s2);
}
}
Iterator<String> it = res.iterator();
while(it.hasNext())
{
if(it.next().length() < maxCount)
{
it.remove();
}
}
return res;
}
public static String getPalindromesubstring(String s , int left, int right)
{
while(left >=0 && right <s.length() && s.charAt(left) == s.charAt(right))
{
left--;
right++;
}
return s.substring(left+1, right);
}
}
import java.util.*;
public class LongestPalindromicSubstring {
public static void main(String[] args)
{
String s1 = "cb b d";
List<String> res1 = getLongestPalindromicSubstring(s1);
System.out.println(res1);
}
public static List<String> getLongestPalindromicSubstring(String s)
{
List<String> res = new ArrayList<>();
int maxLen = 0;
for(int i = 0; i< s.length()-1; i++)
{
String s1 = getPalindromicSubstring(s, i, i);
String s2 = getPalindromicSubstring(s,i, i+1);
maxLen = Math.max(maxLen, Math.max(s1.length(), s2.length()));
if(s1.length() == maxLen)
{
res.add(s1);
}
if(s2.length() == maxLen)
{
res.add(s2);
}
}
Iterator<String> it = res.iterator();
while(it.hasNext())
{
if(it.next().length() < maxLen)
{
it.remove();
}
}
return res;
}
public static String getPalindromicSubstring(String s, int left, int right)
{
while(left >=0 && !isValid(s.charAt(left)))
{
left--;
}
while(right < s.length() && !isValid(s.charAt(right)))
{
right++;
}
while(left >=0 && right < s.length() && Character.toLowerCase(s.charAt(left)) == Character.toLowerCase(s.charAt(right)))
{
left--;
right++;
}
return s.substring(left+1, right);
}
public static boolean isValid(char c)
{
return Character.isLetter(c) || Character.isDigit(c);
}
}