LeetCode 125.验证回文串
2019-08-06 17:09
417 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/twistfatey/article/details/98634481
题目:
题目地址:https://leetcode-cn.com/problems/valid-palindrome/
问题描述:
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: “A man, a plan, a canal: Panama”
输出: true
示例 2:输入: “race a car”
输出: false来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-palindrome
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
我的解题思路:
双指针法:
- 将字符串中的字母都转为小写,方便比较
- 字符串转成字符数组
- 因为题目只比较字母和数字,使用 Character.isLetterOrDigit 方法,如果不是字母或数字,则指针移动直到符合条件
- 对比左指针和右指针的字符是否相同,相同就移动指针,进入下一个循环
public static boolean isPalindrome(String s) { int left=0; int right=s.length()-1; String lowerCase=s.toLowerCase();//字符串中的字母都转为小写,方便比较 char[] chars=lowerCase.toCharArray(); while (left<right){ while ((!Character.isLetterOrDigit(chars[left]))&&left<right){ left++; } while ((!Character.isLetterOrDigit(chars[right]))&&left<right){ right--; } if (chars[left]!=chars[right]){ return false; } left++; right--; } return true; }
相关文章推荐
- LeetCode 125.验证回文串
- LeetCode-125.验证回文串(相关话题:字符串)
- LeetCode - 125. 验证回文串
- LeetCode 125. 验证回文串
- Leetcode刷题28-125.验证回文串(C++)
- Leetcode:125.验证回文串
- Leetcode 125. 验证回文串
- Python LeetCode(125.验证回文串)
- Leetcode题库 - 验证回文串(java语言版)
- leetcode 125 验证回文串
- [leetcode]验证回文串[javascript]
- LeetCode125-验证回文串
- LeetCode 125. Valid Palindorme (验证回文字符串)
- leetcode-125-验证回文串
- 验证回文串--leetcode第125题
- leetcode-125-验证回文串
- leetcode-125. Valid Palindrome(验证含有标点符号String是否为回文串)
- 验证回文串 - LeetCode
- LeetCode之最大回文串--动态规划
- 【LeetCode-面试算法经典-Java实现】【020-Valid Parentheses(括号验证)】