LeetCode 125. Valid Palindrome

原题链接在这里:https://leetcode.com/problems/valid-palindrome/

题目:

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

题解:

注意在用Character.isLetterOrDigit(s.charAt(i)) 前需检验 i 是否index out of bound 了.

Note: if first check i < j.

Time Complexity: O(n), n = s.length().

Space: O(1).

AC Java:

复制代码
 1 class Solution {
 2     public boolean isPalindrome(String s) {
 3         if(s == null || s.length() == 0){
 4             return true;
 5         }
 6         
 7         int i = 0;
 8         int j = s.length() - 1;
 9         while(i < j){
10             while(i < j && !Character.isLetterOrDigit(s.charAt(i))){
11                 i++;
12             }
13             
14             while(i < j && !Character.isLetterOrDigit(s.charAt(j))){
15                 j--;
16             }
17             
18             if(i < j && Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))){
19                 return false;
20             }
21             
22             i++;
23             j--;
24         }
25         
26         return true;
27     }
28 }
复制代码

AC C++:

复制代码
 1 class Solution {
 2 public:
 3     bool isPalindrome(string s) {
 4         int l = 0;
 5         int r = s.length() - 1;
 6         while(l < r){
 7             while(l < r && !isalnum(s[l])){
 8                 l++;
 9             }
10 
11             while(l < r && !isalnum(s[r])){
12                 r--;
13             }
14 
15             if(tolower(s[l]) != tolower(s[r])){
16                 return false;
17             }
18 
19             l++;
20             r--;
21         }
22 
23         return true;
24     }
25 };
复制代码

AC Python:

复制代码
 1 class Solution:
 2     def isPalindrome(self, s: str) -> bool:
 3         l, r = 0, len(s) - 1
 4         while l < r:
 5             while l < r and not s[l].isalnum():
 6                 l += 1
 7             while l < r and not s[r].isalnum():
 8                 r -= 1
 9             if s[l].lower() != s[r].lower():
10                 return False
11             l += 1
12             r -= 1
13         return True
复制代码

跟上Valid Palindrome II.

posted @   Dylan_Java_NYC  阅读(217)  评论(0)    收藏  举报
编辑推荐:
· 复杂业务系统线上问题排查过程
· 通过抓包,深入揭秘MCP协议底层通信
· 记一次.NET MAUI项目中绑定Android库实现硬件控制的开发经历
· 糊涂啊!这个需求居然没想到用时间轮来解决
· 浅谈为什么我讨厌分布式事务
阅读排行:
· 那些年我们一起追过的Java技术,现在真的别再追了!
· 还在手写JSON调教大模型?.NET 9有新玩法
· 为大模型 MCP Code Interpreter 而生:C# Runner 开源发布
· 面试时该如何做好自我介绍呢?附带介绍样板示例!!!
· JavaScript 编年史:探索前端界巨变的幕后推手
点击右上角即可分享
微信分享提示