验证回文串
题目形容:给定一个字符串,验证它是否是回文串,只思考字母和数字字符,能够疏忽字母的大小写。
阐明:本题中,咱们将空字符串定义为无效的回文串。
示例阐明请见LeetCode官网。
起源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl...
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。
解法一:字符串遍历
次要是应用一些库函数来遍历字符串。
首先,如果s是空或者s的长度为1,则间接返回true;
否则,从s的第一位front和最初一位end开始遍历,遍历过程为:
- 如果front对应地位的字符frontChar不是字母或数字字符,则front向后挪一位,进行下一轮遍历;
- 如果end对应地位的字符endChar不是字母或数字字符,则end向前挪一位,进行下一轮遍历;
- 如果front和end对应地位的字符都是字母或者数字字符,首先,如果frontChar或endChar是字母,则先将之转化为大写字符(因为不须要辨别大小写),而后比拟frontChar和endChar是否相等,如果不相等,则返回false;如果相等,则front向后挪一位,同时end向前挪一位,进行下一轮遍历。
- 遍历完结的条件就是front不小于end。
public class LeetCode_125 { public static boolean isPalindrome(String s) { if (s == null || s.length() == 1) { return true; } int front = 0, end = s.length() - 1; while (front <= end) { char frontChar = s.charAt(front); char endChar = s.charAt(end); if ((frontChar >= 'a' && frontChar <= 'z') || (frontChar >= 'A' && frontChar <= 'Z') || (frontChar >= '0' && frontChar <= '9')) { if ((endChar >= 'a' && endChar <= 'z') || (endChar >= 'A' && endChar <= 'Z') || (endChar >= '0' && endChar <= '9')) { if (Character.isAlphabetic(frontChar)) { frontChar = Character.toUpperCase(frontChar); } if (Character.isAlphabetic(endChar)) { endChar = Character.toUpperCase(endChar); } if (frontChar != endChar) { return false; } else { front++; end--; } } else { end--; } } else { front++; } } return true; } public static void main(String[] args) { System.out.println(isPalindrome("A man, a plan, a canal: Panama")); }}
【每日寄语】 人生似水岂无崖,浮云吹作雪,世味煮成茶。