#力扣:125. 验证回文串@FDDLC

125. 验证回文串

一、Java

class Solution {
    public boolean isPalindrome(String s) {
        for (int l = 0, r = s.length() - 1; l < r; l++, r--) {
            while (l < r && !Character.isLetterOrDigit(s.charAt(l))) l++;
            while (l < r && !Character.isLetterOrDigit(s.charAt(r))) r--;
            if (l < r && Character.toLowerCase(s.charAt(l)) != Character.toLowerCase(s.charAt(r))) return false;
        }
        return true;
    }
}

二、C++

#include 

using namespace std;

class Solution {
public:
    bool isPalindrome(string s) {
        for (int l = 0, r = s.size() - 1; l < r; l++, r--) {
            while (l < r && !isalnum(s[l])) l++;
            while (l < r && !isalnum(s[r])) r--;
            if (l < r && tolower(s[l]) != tolower(s[r])) return false;
        }
        return true;
    }
};

三、Python

class Solution:
    def isPalindrome(self, s: str):
        l, r = 0, len(s) - 1
        while l < r:
            while l < r and not s[l].isalnum():
                l += 1
            while l < r and not s[r].isalnum():
                r -= 1
            if l < r and s[l].lower() != s[r].lower():
                return False
            l, r = l + 1, r - 1
        return True

四、JavaScript

var isPalindrome = function(s) {
    for (let l = 0, r = s.length - 1; l < r; l++, r--) {
        while (l < r && !/[a-zA-Z0-9]/.test(s[l])) l++;
        while (l < r && !/[a-zA-Z0-9]/.test(s[r])) r--;
        if (l < r && s[l].toLowerCase() !== s[r].toLowerCase()) return false;
    }
    return true;
};

五、Go

package main

import "unicode"

func isPalindrome(s string) bool {
	for l, r := 0, len(s)-1; l < r; l, r = l+1, r-1 {
		for l < r && !unicode.IsDigit(rune(s[l])) && !unicode.IsLetter(rune(s[l])) {
			l++
		}
		for l < r && !unicode.IsDigit(rune(s[r])) && !unicode.IsLetter(rune(s[r])) {
			r--
		}
		if l < r && unicode.ToLower(rune(s[l])) != unicode.ToLower(rune(s[r])) {
			return false
		}
	}
	return true
}

你可能感兴趣的:(力扣刷题:Java,C++,Python,JS,Go,leetcode,算法,职场和发展)