本文共 1322 字,大约阅读时间需要 4 分钟。
LeetCode刷题:125. 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
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: "A man, a plan, a canal: Panama"输出: true
示例 2:
输入: "race a car"输出: false
算法设计
package com.bean.algorithm.basic;public class ValidPalindrome { public static boolean isPalindrome(String input) { input = input.toLowerCase(); input = input.replaceAll("[^0-9a-zA-Z]", ""); int j = input.length(); for (int i = 0; i < input.length(); i++) { String fword = input.substring(i, i + 1); String lword = input.substring(j - 1, j); if (!fword.equals(lword)) { return false; } if (i == j) { return true; } j--; } return true; } public static void main(String[] args) { // TODO Auto-generated method stub /* * Input: "A man, a plan, a canal: Panama" * Output: true */ ValidPalindrome validPalindrome=new ValidPalindrome(); String input="A man, a plan, a canal: Panama"; boolean flag=validPalindrome.isPalindrome(input); System.out.println("Flag is: "+flag); }}
程序运行结果:
Flag is: true
转载地址:http://ajtdi.baihongyu.com/