赞
踩
有限状态机 说白了就是根据不同的字符串状态,去归类
function stringMatcher(input) { // 定义状态 const states = { START: 'START', A: 'A', B: 'B', REJECT: 'REJECT', ACCEPT: 'ACCEPT', }; // 定义状态转换规则 const transitions = [ { from: states.START, to: states.A, input: 'a' }, { from: states.A, to: states.A, input: 'a' }, { from: states.A, to: states.B, input: 'b' }, { from: states.B, to: states.B, input: 'b' }, { from: states.B, to: states.REJECT, input: 'a' }, ]; // 初始状态为 START let currentState = states.START; // 遍历输入字符串 for (const char of input) { let nextState = states.REJECT; // 查找下一个状态 for (const transition of transitions) { if (transition.from === currentState && transition.input === char) { nextState = transition.to; break; } } // 如果没有找到下一个状态,则字符串不符合规则 if (nextState === states.REJECT) { return false; } currentState = nextState; } // 如果最终状态是 ACCEPT,则字符串符合规则 return currentState === states.B; } // 测试字符串匹配 console.log(stringMatcher('ab')); // true console.log(stringMatcher('aaab')); // false console.log(stringMatcher('abb')); // false console.log(stringMatcher('abab')); // false console.log(stringMatcher('')); // false
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。