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

65 阅读2分钟
let reg1 = new RegExp('b', "g");
undefined
let str = 'abcdefg';
undefined
reg1.exec(str)
['b', index: 1, input: 'abcdefg', groups: undefined]
reg1.exec(str)
null
reg1.exec(str)
['b', index: 1, input: 'abcdefg', groups: undefined]
reg1.exec(str)

exec全局查找,如果查找到符合正则表达式的结果,返回一个对象,0是查找到的字符,index是该字符下标,input是整个字符串,然后执行多义词exec,会从该下下标后字符串全局查找,直到查找到的结果是null,又从下表0开始查,如此反复


let reg1 = new RegExp('b', "g");
undefined
let str = 'abcdefgb';
undefined
reg1.exec(str);
['b', index: 1, input: 'abcdefgb', groups: undefined]
reg1.exec(str);
['b', index: 7, input: 'abcdefgb', groups: undefined]
reg1.exec(str);
null

reg1.exec(str);
['b', index: 1, input: 'abcdefgb', groups: undefined]
reg1.exec(str);
['b', index: 7, input: 'abcdefgb', groups: undefined]
reg1.exec(str);
null

// 第一种方法,使用exec方法
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;
}

变种:可参考,第一种好点
const str = "abcddcbatmnnmdfabc";
function findNoReapetChar(str) {
if (str === null || str === "") return null;
if (str.length === 1) return str;
const len = str.length,
  map = {};
for (let i = 0; i < len; i++) {
  const c = str[i];
  console.log('循环:', c, map)
  if (!map[c] && str.indexOf(c, i + 1) == -1) {
    return c;
  }
  map[c] = true; // 重复
}
return null;
}



**字符串的match:**
let str = 'abcdefg';
undefined
str.match(/g/)
['g', index: 6, input: 'abcdefg', groups: undefined]
str.match(/g/)
['g', index: 6, input: 'abcdefg', groups: undefined]
str.match(/g/)
['g', index: 6, input: 'abcdefg', groups: undefined]
str.match(/a/g)
['a']
str.match(/h/g)
null

match如果加了全局查询g,如果查找到则返回一个数组,如果没有查找到则返回null,如果不加全局查找,则返回一个对象,没有查找到则返回null,这里和正则表达式的exec不一样,重复调用,得到的结果是一样的

//第二种方法: 遍历字符串,字符串使用match查找每一个字符的个数
let 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++) {
  let c = str[i];
  let reg = new RegExp(c, "g");
  if (str.match(reg).length === 1) {
    return c;
  }
}
return null;
}


// 方法三:速度最快
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;
}

let s = findNoReapetChar(str);
console.log("结果:", s); // t