-
Notifications
You must be signed in to change notification settings - Fork 639
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
百度:实现一个函数,判断输入是不是回文字符串 #20
Labels
Comments
方法一: 用首尾两个指针,向中间扫描字符串,如果两指针指向的字符都一样, 这字符串就是一个回文。时间复杂度:O(n),空间复杂度:O(1) /** 判断是不是回文字符串
* @param {string} str
* return Boolean
*/
function IsPalindrome(str) {
if (str === null || str.length < 1) {
return false
}
let left = 0, right = str.length - 1
while(left < right) {
if(str.charAt(left) !== str.charAt(right)) {
return false
}
++left;
--right;
}
return true
} |
解法一:使用APIfunction isPlalindrome(input) {
if (typeof input !== 'string') return false;
return input.split('').reverse().join('') === input;
} 解法二:不使用APIfunction isPlalindrome(input) {
if (typeof input !== 'string') return false;
let i = 0, j = input.length - 1
while(i < j) {
if(input.charAt(i) !== input.charAt(j)) return false
i ++
j --
}
return true
} |
/**
* 判断字符串是否是回文字符串
* @param {*} str
*/
function isReverseString(str) {
if (typeof str !== 'string') return false;
// 方法1:reverse
// return str.split('').reverse().join('') === str;
// 方法2
const strArr = str.split('');
let reverseStr = '';
let len = strArr.length - 1;
while (len >= 0) reverseStr += strArr[len--];
return str === reverseStr;
}
console.log(isReverseString('asddsa')); // true
console.log(isReverseString('asdDsa')); // false
console.log(isReverseString('13dffd31')); // true |
const isPalindrome = () => {
const len = str.length
const halfLen = len / 2
for (let i = 0; i < halfLen; i++) {
if (str[i] !== str[ len - i - 1 ]) {
return false
}
}
return true
}
|
双指针 function isReverseString(str) {
var half = str.toString().length / 2 | 0
var l = 0
var r = str.length - 1
while (l != half) {
if (str[l++] != str[r--]) return false
}
return true
}
var { log } = console
log(isReverseString('12321'))
log(isReverseString('123321'))
log(isReverseString('234')) |
function isPalindrome(str){
let i = 0,k = str.length-1
let flg = true
while(i<k&&flg){
if(str.charAt(i)!==str.charAt(k)){
flg= false
}
i++
k--
}
return flg
}
console.log(isPalindrome('aabbccdccbbaa'))
console.log(isPalindrome('aabbccdvsccbbaa')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: