美文网首页程序员
力扣 125 验证回文串

力扣 125 验证回文串

作者: zhaojinhui | 来源:发表于2020-08-20 09:34 被阅读0次

题意:给一个string,判断是否是回文

思路:设两个指针,s和e分别指向string的首尾,遍历字符串

  1. 从首向后找到一个合法的字符
  2. 从尾向前找到一个合法的字符
  3. 如果首尾字符不等返回false,相等重复1,2,3
  4. 如果首<尾,推出循环
  5. 返回true

思想:首尾指针

复杂度:时间O(n),空间O(1)

class Solution {
    public boolean isPalindrome(String str) {
        int s = 0;
        int e = str.length() - 1;
        str = str.toLowerCase();
        while(s<e) {
            while(s<e) {
                if (('a' <= str.charAt(s) && 'z' >= str.charAt(s)) 
                    || ('0' <= str.charAt(s) && '9' >= str.charAt(s)))
                    break;
                s++;
            }
            while(s<e && ('a' > str.charAt(e) || 'z' < str.charAt(e))) {
                if (('a' <= str.charAt(e) && 'z' >= str.charAt(e)) 
                    || ('0' <= str.charAt(e) && '9' >= str.charAt(e)))
                    break;
                e--;
            }
            if(str.charAt(s) != str.charAt(e))
                return false;
            s++;
            e--;
        }
        return true;
    }
}

相关文章

网友评论

    本文标题:力扣 125 验证回文串

    本文链接:https://www.haomeiwen.com/subject/uvfsjktx.html