我正在尝试编写代码以确定字符串是否是回文。我将字符串小写,取出空格,然后将其变成数组。接下来,我将其分成两半,反转后半部分,然后比较这两个数组以查看字符串是否是回文。该功能将不会记录为真。
let string = "Never odd or even";
let lowerString = string.toLowerCase();
let split = lowerString.split("");
let array = split.filter(noSpaces);
function noSpaces(i) {
return i !== " ";
}
function checkIfPal() {
if (array.length % 2 === 1) {
let firstHalf = array.slice(0, array.length / 2);
let secondHalf = array.slice(array.length / 2 + 1, array.length);
let revSecondHalf = [];
for (let i = secondHalf.length - 1; i > -1; i--) {
revSecondHalf.push(secondHalf[i]);
}
if (firstHalf === revSecondHalf) {
console.log("true for odd");
} else {
console.log("false for odd");
}
} else {
let firstHalf = array.slice(0, array.length / 2);
let secondHalf = array.slice(array.length / 2, array.length);
let revSecondHalf = [];
for (let i = secondHalf.length - 1; i > -1; i--) {
revSecondHalf.push(secondHalf[i]);
}
if (firstHalf === revSecondHalf) {
console.log("true for even");
} else {
console.log("false for even");
}
}
}
checkIfPal();
答案 0 :(得分:2)
有一种更简单的方法。
function isPalindrome(str) {
str = str.replace(/[^\w\d]/g, '').toLowerCase();
const len = str.length;
for (let i = 0; i < len / 2; i++) {
if (str[i] !== str[len - 1 - i]) {
return false;
}
}
return true;
}
console.log(isPalindrome('A man, a plan, a canal, Panama!'));
console.log(isPalindrome('Mr. Owl Ate My Metal Worm'));
console.log(isPalindrome('A Santa Lived As a Devil At NASA'));
然后是超级简单的方法,但是在长字符串处理方面不是很有效。
function isPalindrome(str) {
str = str.replace(/[^\w\d]/g, '').toLowerCase();
return str === str.split('').reverse().join('');
}
console.log(isPalindrome('A man, a plan, a canal, Panama!'));
console.log(isPalindrome('Mr. Owl Ate My Metal Worm'));
console.log(isPalindrome('A Santa Lived As a Devil At NASA'));
答案 1 :(得分:0)
在这一行
class DrinkMenu extends Component {
constructor(props, context) {
super(props, context);
this.state = {
show: false
};
this.handleHide = this.handleHide.bind(this);
}
handleHide() {
this.setState({ show: false });
}
async componentDidMount() {
let res = await axios.get('/getAllDrinks')
this.props.updateDrinkMenu(res.data)
}
async addToCart(drinkObj) {
let res = await axios.post('/addToCart', drinkObj)
console.log(`Added ${drinkObj.name} to order.`)
}
render() {
let drinkList = this.props.drinkMenu.map((drink) => {
return (
<div key={drink.id}>
<h5>{drink.name}</h5>
<h6>${drink.price}</h6>
<span
onClick={() => this.setState({ show: true })}
>
<strong>More Info</strong>
<br />
<button onClick={() => this.addToCart(drink)}>Add to Order</button>
</span>
<Modal
show={this.state.show}
onHide={this.handleHide}
container={this}
aria-labelledby="contained-modal-title"
>
<Modal.Header closeButton>
<Modal.Title id="contained-modal-title">
{drink.name}
</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>{drink.sub_category} | ABV {drink.abv}% | {drink.origin}</p>
<Col xs={6} md={4}>
<Image className="drink-logo" src={drink.logo} thumbnail />
</Col>
<p className="drink-description"><strong>Description</strong><br />{drink.description}</p>
<p href={drink.website}>Website</p>
</Modal.Body>
<Modal.Footer>
<Button onClick={this.handleHide}>Close</Button>
</Modal.Footer>
</Modal>
</div>
)
})
return (
<div>
<h2>Drink Menu</h2>
<div>
{drinkList}
</div>
</div>
)
}
}
您正在尝试比较两个数组,但是JavaScript不允许您使用if (firstHalf === revSecondHalf) {
进行比较,因为它们是两个不同的对象。将每个数组===
转换为字符串,然后进行比较,或者循环比较一个数组中的元素,将它们与另一个数组中相同索引的元素进行比较。
前一种方法更容易。
答案 2 :(得分:0)
在脚本中,您正在使用===
比较两个数组对象。
如果比较中的变量引用了完全相同的数组对象,则它将返回true
。但是,如果它们指向两个不同的数组对象,即使它们的内容相同,它将始终返回false
。
如果您希望继续使用数组进行比较,则需要检查数组的每个元素是否相同。
function compareArrayElements(arr1, arr2) {
if (arr1.length != arr2.length)
return false;
for (var i=0;i<arr1.length;i++) {
if (arr1[i] != arr2[i])
return false;
}
return true;
}
现在有了解决方案,您可以对其进行优化并减少for循环的次数。
答案 3 :(得分:0)
一种基于将数组与反向数组进行比较的算法:
const isPalindrome = (str) => {
//Eliminate punctuation and spaces
// Force lower case
// Split
let arr = str.toString().replace(/[^A-Za-z0-9_]/g, "").toLowerCase().split('');
// Join into one word
let joined = arr.join('');
// Reverse adn join into one word
let reverseJoined = arr.reverse().join('');
//compare
return joined == reverseJoined;
}
console.log(isPalindrome('Red rum, sir, is murder'));
console.log(isPalindrome(404));
console.log(isPalindrome('Red rum, sir'));
console.log(isPalindrome(500));