1. 程式人生 > >leetcode Valid Palindrome

leetcode Valid Palindrome

迴文校驗題目:https://leetcode.com/problems/valid-palindrome/

解題思路:

1.把字串全部小寫

2.使用兩個指標,一個指向字串的頭,一個值向字串的尾,如果不是字母,頭指標向後移動,尾指標向後移動,

 

public static void main(String[] args) {
		String str="A man, a plan, a canal: Panama";
		boolean palindrome = isPalindrome(str);
		System.out.println(palindrome);
	}
	public  static boolean isPalindrome(String s) {
		s = s.toLowerCase();
		int i=0;
		int j=s.length()-1;
		char c;
		char d;
		while(i<j){
			c = s.charAt(i);
			d = s.charAt(j);
			if(!isNumbersAndLetters(c)){
				i++;
			}
			if(!isNumbersAndLetters(d)){
				j--;
			}
			if(isNumbersAndLetters(c)&&isNumbersAndLetters(d)){
				if(c==d){
					i++;
					j--;
				}else{
					return false;
				}
			}
		}
		return true;
	}
	public static  boolean isNumbersAndLetters(char c){
		if((c>='a' && c<='z')|| (c>='A' && c<='Z') || (c>='0' &&c<='9')){
			return true;
		}
		return false;
	}