码迷,mamicode.com
首页 > 编程语言 > 详细

【初级算法】16. 验证回文字符串

时间:2018-05-03 14:24:02      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:nbsp   star   AC   rac   数字   public   题目   cond   ++   

题目:

给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。

说明:本题中,我们将空字符串定义为有效的回文串。

示例 1:

输入: "A man, a plan, a canal: Panama"
输出: true
示例 2:

输入: "race a car"
输出: false

1.解题思路:

本题比较简单,直接取字符串的前后字母进行比对,如果相等则前进,否则返回错误。

 

class Solution {
public:
    bool isPalindrome(string s) {
        int len = s.size();
        int start = 0;
        int end = len-1;
        
        while(start < end){
            char first,second;
            /*get the fisrt char*/
            while(start <= end){
                if((s[start] >= a && s[start] <= z)||
                   (s[start] >= A && s[start] <= Z)||
                   (s[start] >= 0 && s[start] <= 9)){
                    first = s[start];
                    if(s[start] >= A && s[start] <= Z){
                        first = first-A+a;
                    }
                    break;
                }else{
                    start++;
                }
            }
            
            /*get the second char*/
            while(start <= end){
                if((s[end] >= a && s[end] <= z)||
                   (s[end] >= A && s[end] <= Z)||
                   (s[end] >= 0 && s[end] <= 9)){
                    second = s[end];
                    if(second <= Z&&second>=A){
                        second = second-A+a;
                    }
                    break;
                }else{
                    end--;
                }
            }
            
            if(start > end){
                break;
            }
            
            if(first == second){
                start++;
                end--;
            }else{
                return false;
            }
        }
        
        return true;
    }
};

 

【初级算法】16. 验证回文字符串

标签:nbsp   star   AC   rac   数字   public   题目   cond   ++   

原文地址:https://www.cnblogs.com/mikemeng/p/8984856.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!