(Java)leetcode-125 Valid Palindrome

topic

【有效回文串】
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

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

Example 1:

Input: “A man, a plan, a canal: Panama”
Output: true
Example 2:

Input: “race a car”
Output: false

Ideas 1

We must first delete extraneous characters, you can use regular expressions to match and remove, ignore case because the title description, followed by the characters in the string into all lowercase. This inversion speaking string as a new string, then the string can compare the old and new.

Code 1

public class Solution {
    public boolean isPalindrome(String s) {
    	if (s.isEmpty()) {
        	return true;
        }
        String actual = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase();//删除所有的:非字母数字字符,并讲所有的大写字母转换为小写字母
        String rev = new StringBuffer(actual).reverse().toString();//将字符串进行反转
        return actual.equals(rev);//比较
    }
}

Submitted 1 results

Runtime: 15 ms, faster than 28.86% of Java online submissions for Valid Palindrome.
Memory Usage: 40.3 MB, less than 10.36% of Java online submissions for Valid Palindrome.

Ideas 2

Double pointer, a one, while ensuring the character pointer premise letters or numbers, each pointing character is determined (after lowercase) are equal. Since no character to match, so the idea of ​​efficiency than 1 higher.

Code 2

public class Solution {
    public boolean isPalindrome(String s) {
        if (s.isEmpty()) {
        	return true;
        }
        int head = 0, tail = s.length() - 1;//首尾指针
        char cHead, cTail;
        while(head <= tail) {
        	cHead = s.charAt(head);//更新字符
        	cTail = s.charAt(tail);
        	if (!Character.isLetterOrDigit(cHead)) {
        		head++;//若首指针指向的字符非字母或非数字,则指针后移
        	} else if(!Character.isLetterOrDigit(cTail)) {
        		tail--;//若尾指针指向的字符非字母或非数字,则指针前移
        	} else {
        		if (Character.toLowerCase(cHead) != Character.toLowerCase(cTail)) {
        			return false;//回文检测不通过
        		}
        		head++;//移动指针,继续检测
        		tail--;
        	}
        }//while
        
        return true;//通过检测
    }
}

Present the results

Runtime: 4 ms, faster than 83.24% of Java online submissions for Valid Palindrome.
Memory Usage: 37.8 MB, less than 56.88% of Java online submissions for Valid Palindrome.

to sum up

The key method:

s.replaceAll(String regex, String replacement);
s.toLowerCase();
s1.equals(s2);
bf.reverse().toString();
Character.toLowerCaese();
Character.isLetterOrDigit();
Published 143 original articles · won praise 45 · views 70000 +

Guess you like

Origin blog.csdn.net/z714405489/article/details/89518992