Check String Palindrom

Question

Given a string S and check if S is the palindrome

判断字符串是否是回文字符串。

Solution 1:

可以直接想到i 跟 n - i -1 进行比较。时间复杂度O(N)

class Solution:
    # @param s, a string
    # @return a list of lists of string
    def isPalindrome(self, s):
        for i in range(len(s)):
            if s[i] != s[len(s)-1-i]: return False
        return True

Solution 2:

使用左右指针解题思路更清晰 而且便于扩展。

class Solution:
    # @param s, a string
    # @return a list of lists of string
    def isPalind(self, s):
        start, end = 0, len(s) - 1
        while start < end:
            if s[start] != s[end]:
                return False
            start += 1
            end -= 1
        return True

变型题:忽略空格特殊字符,然后比较

public class Solution {
    public bool IsPalindrome(string s) {
        if(string.IsNullOrEmpty(s))
        {
          return true;
        }
        s = s.ToLower();
        s = s.Trim();
        int left = 0;
        int right = s.Length - 1;

        while(left < right){

            while(left < right && !Char.IsLetter(s[left]) && !Char.IsNumber(s[left])){
               left++;
            }
            while(left < right && !Char.IsLetter(s[right]) && !Char.IsNumber(s[right])){
               right--;
            }

            if(s[left] != s[right]){
               return false;
            }

            left++;
            right--;
        }
        return true;
    }
}

Last updated

Was this helpful?