每日一道算法题 - SimpleSymbols(easy-5)

本文介绍了一个简单的符号验证算法实现,该算法使用JavaScript编写,用于判断字符串中字母是否被+符号正确包围。文中提供了两种实现方法及测试案例。

虽然都是很简单的算法,每个都只需5分钟左右,但写起来总会遇到不同的小问题,希望大家能跟我一起每天进步一点点。
更多的小算法练习,可以查看我的文章。

规则

Using the JavaScript language, have the function SimpleSymbols(str) take the str parameter being passed and determine if it is an acceptable sequence by either returning the string true or false. The str parameter will be composed of + and = symbols with several letters between them (ie. ++d+===+c++==a) and for the string to be true each letter must be surrounded by a + symbol. So the string to the left would be false. The string will not be empty and will have at least one letter.

使用JavaScript语言,让函数SimpleSymbols(str)获取传递的str参数,并通过返回字符串truefalse来确定它是否满足要求。
str参数将由+=与它们之间的若干字母符号组成(即, ++d+===+C++==a)。
当每个字母都被+包围时(如 +a+),返回true,否则(如 a+)返回false
ps:该字符串不会为空,并且至少有一个字母。

测试用例

Input:"+d+=3=+s+"
Output:"true"

Input:"f++d+"
Output:"false"

Input:"++f+a+d"
Output:"false"

my code

function SimpleSymbols(str) {
    if (str[0].match(/[a-z]/i) || str[str.length - 1].match(/[a-z]/i)) return false

    for (var i = 1; i < str.length - 1; i++) {
        if (!str[i].match(/[a-z]/i)) continue

        if (str[i - 1] !== '+' || str[i + 1] !== '+') return false
    }

    return true;
}

other code

code-1

function SimpleSymbols(str) {
    if (/^[a-zA-Z]/.test(str) || /[a-zA-Z]$/.test(str)) {
        return false;
    }
    if (/[^+][a-zA-Z]/.test(str) || /[a-zA-Z][^+]/.test(str)) {
        return false;
    }
    return true;
}

code-2

function SimpleSymbols(str) { 
    return (str).match(/([^+][a-z])|([a-z][^+])/gi) === null; 
}

思路

方法1: 通过字符串的遍历,检查每个字母是否被+包围

方法2:使用正则去匹配

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值