我的字符串输入如下所示:
const text = '<Jane>:flower: <Kate><john> :like: received:flower::flower:'
个
我需要编写一个函数,它将计算每个人有多少朵花.昵称总是以这样的模式放入标签中:<nickname>
,它们不区分大小写.因此,每个nick都应该以小写形式保存.
解析nick后,程序应该搜索子字符串":flower:"并计算它被满足的次数.如果有一个以上的缺口,一个接一个,那么它们应该被链在一起.所以所有的":flower:"子字符串count,也就是跟在它们后面的子字符串,都应该被添加到每个nick中.
如果在文本中两次遇到相同的尼克,则将其后的花朵计数添加到结果对象中保存的计数中.
如果在一个刻痕链组中遇到相同的刻痕,例如:
<John><John><John> :flower: <Kate>
.
然后,每次遇到缺口时,它都会在这一连串缺口之后添加花的数量.所以,在这个例子中,Jogn得到了三朵花,而Kate没有得到,因为她在她的nick之后没有花.
但是,我只能使用:
- 正好一个for循环;
- 存储如下结果的一个对象:
{ jane: 1, kate: 2, john: 2 }
个
我不能使用数组、嵌套循环、原生JS方法(toLowerCase()除外)或正则表达式.有人能帮我这个忙吗?
我一直在思考如何在不使用数组的情况下将昵称"链接在一起".我有这样的代码,它只是返回一个对象,它包含所有的刻痕,文本中有.
function countFlowers(text) {
const nickTag = "<>";
const result = {};
let isParsingNick = false;
let currentNick = '';
let nickTagIndex = 0;
for (let i = 0; i < text.length; i++) {
const current = text[i];
if (!isParsingNick && current === nickTag[nickTagIndex]) {
if (nickTagIndex === 0) {
isParsingNick = true;
currentNick = '';
}
nickTagIndex++;
} else if (isParsingNick && current === nickTag[nickTagIndex]) {
if (nickTagIndex === 1) {
isParsingNick = false;
result[currentNick] = 0;
nickTagIndex = 0;
continue;
}
nickTagIndex++;
} else if (isParsingNick && current !== nickTag[nickTagIndex]) {
currentNick += current.toLowerCase();
}
}
return result;
}
const text = '<Jane>:flower: <Kate><john> :like: received:flower::flower:'
console.log(countFlowers(text))
输入和结果的更多示例:
1. const text = '<Jane>:flower: <kate>:like:<John> :like:
received:flower::flower:'
// {
// jane: 1,
// kate: 2,
// john: 2
// }
2. const text = '<Jane>:flower: <kate>:flower: :flower: :flower: <John> :like: received:flower::flower:'
// {
// jane: 1,
// kate: 3,
// john: 2,
// }
3. const text = '<Jane>:flower: <kate>:flower flower: flower:<John> :like: received:flower::flower:'
//because between kate and john there are no valid :flower: then they
are grouped together
// {
// jane: 1,
// kate: 2,
// john: 2,
// }
4. const text = '<Jane>:flower: <kate>:like:<John> :like:
received:flower::flower: <Jane> alsdaksdjhsa <Jane> :flower: :flower:'
// {
// jane: 5,
// kate: 2,
// john: 2
// }
5. const text = '<Jane>:flower: <kate><Kim><Jacob><Emily> :like: received:flower::flower: <Kim><Jacob><Jane>'
// {
// jane: 1
// kate:2
// kim:2
// jacob:2
// emily:2
// }
6. const text = ':flower: :flower: <Jane>:flower: <kate><John> :like: received:flower::flower: '
//if there are flowers not after nickname - they are skipped
// {
// jane: 1,
// kate: 2,
// john: 2,
// }