ARTS-14--回文字符串的解法

84 阅读1分钟

概述:
左耳朵耗子专栏《左耳听风》 用户自发每周完成一个ARTS:

1.Algorithm:每周至少做一个 leetcode 的算法题

2.Review:阅读并点评至少一篇英文技术文章

3.Tip:学习至少一个技术技巧

4.Share:分享一篇有观点和思考的技术文章

Algorithm
题目概述:

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example,
"A man, a plan, a canal: Panama"is a palindrome.
"race a car"is not a palindrome.

Note: 
Have you consider that the string might be empty? This is a good question to ask during an interview.

For the purpose of this problem, we define empty string as valid palindrome.


import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Solution {
       public boolean isPalindrome(String s) {
        if (s == null) {
            return false;
        }
        s = getValidateStr(s);
        int len = s.length();
        char[] chars = s.toCharArray();
        String[] arr = new String[len];
        for (int p=0;p<chars.length;p++) {
            arr[p]= String.valueOf(chars[p]);
        }
        //偶数
        if (len % 2 == 0) {
            int leftIndex = len / 2 - 1;
            int rightIndex = len / 2;
            for (int l = leftIndex, r = rightIndex; l >= 0 && r < len; l--, r++) {
                if (!(arr[l].equals(arr[r]))) {
                    return false;
                }
            }
        } else {
            //奇数
            int midIndex = len / 2;
            for (int i = midIndex - 1, j = midIndex + 1; i >= 0 && j < len; i--, j++) {
                if (!(arr[i].equals(arr[j]))) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 判断是否是合法字符
     *
     * @return
     */
    public String getValidateStr(String str) {
          str=str.toUpperCase();
        String regx = "[A-Za-z0-9]*";
        Matcher m = Pattern.compile(regx).matcher(str);
        StringBuilder stb = new StringBuilder();
        while (m.find()) {
            int start = m.start();
            int end = m.end();
            String matchStr = str.substring(start, end);
            stb.append(matchStr);
        }
        return stb.toString();
    }
}