leetcode-125-Valid Palindrome
生活随笔
收集整理的這篇文章主要介紹了
leetcode-125-Valid Palindrome
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目描述:
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: trueExample 2:
Input: "race a car" Output: false?
要完成的函數(shù):
bool isPalindrome(string s)?
?
說明:
1、給定一個字符串s,要求判斷這個字符串是不是回文串。這道題跟普通題目不一樣的地方在于,字符串中可能會有非字母和非數(shù)字,比如空格符和標點符號,我們需要過濾掉它們。
也有可能會有大小寫字母,也需要大寫轉換為小寫。
2、明白題意,我們構造代碼如下:(附詳解)
bool isPalindrome(string s) {int i=0,s1=s.size(),j=s1-1;while(i<j){while(!isalnum(s[i])&&i<=j)//一直找,直到找到字母或者數(shù)字,并且不能超過ji++;if(i==j+1)//如果超過j了,到達j+1,說明從初始的i到j的中間區(qū)域都沒有字母或者數(shù)字,這時候返回true。比如[,.]這樣的例子。return true;while(!isalnum(s[j]))//一直找,直到找到字母或者數(shù)字。這里不加i<=j這個判斷條件是因為,前面在中間區(qū)域找得到,那么這里也必定找得到j--;if(tolower(s[i])==tolower(s[j]))//要轉換大小寫{i++;j--;}elsereturn false;}return true;}上述代碼實測10ms,beats 95.16% of cpp submissions。
轉載于:https://www.cnblogs.com/chenjx85/p/9105513.html
總結
以上是生活随笔為你收集整理的leetcode-125-Valid Palindrome的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Keras Data augmenta
- 下一篇: Sass函数-数字函数-floor()函