JS算法-字符串中第一个不重复字符

1,039 阅读1分钟

本文介绍一种查找字符串中第一个不重复字符的方法。(剑指 Offer 50)

找到字符串中第一个不重复字符

方法一:
const str = 'abcddcbatmnnmdfabc';
function findNoReapetChar(str) {
    if (str === null || str === "") return null;
    if (str.length === 1) return str;
    const len = str.length;
    for(let i = 0; i < len; i++) {
        const c = str[i];
        // 两个判断条件:
        // 1. 该字符是第一个出现的字符
        // 2. 该字符在后边不会再次出现
        if (str.indexOf(c) == i && str.indexOf(c, i+1) === -1) {
            return c;
        }
    }
    return null
}
findNoReapetChar(str);

1.png

方法二:
const str = 'abcddcbatmnnmdfabc';
function findNoReapetChar(str) {
    if (str === null || str === "") return null;
    if (str.length === 1) return str;
    const len = str.length;
    for(let i = 0; i < len; i++) {
        const c = str[i];
        let reg = new RegExp(c, 'g');
        if(reg.exec(str) !== null && reg.exec(str) === null) {
            return c;
        }
    }
    return null;
}
findNoReapetChar(str);

2.png

方法三:
const str = 'abcddcbatmnnmdfabc';
function findNoReapetChar(str) {
    if (str.length === 0) return null;
    if (str.length === 1) return str;
    const len = str.length;
    for(let i = 0; i < len; i++) {
        const c = str[i];
        let reg = new RegExp(c, 'g');
        if (str.match(reg).length === 1) {
            return c;
        }
    }
    return null;
}
findNoReapetChar(str);

总结

本文是剑指 Offer 50题,方法一的速度最快,性能最好,方法二性能较差,方法三正常执行,但提交未成功。