剑指offer

1.替换空格

问题描述:

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为 We Are Happy.则经过替换之后的字符串为 We%20Are%20Happy。

function replaceSpace(str) {
  // write code here
  return str.replace(/s/g, "%20");
}

2.正则表达式匹配

问题描述:

请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含 0 次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配

//s, pattern都是字符串
function match(s, pattern) {
  // write code here
  var reg = new RegExp("^" + pattern + "$", "g");
  return reg.test(s);
}

3.表示数值的字符串

问题描述:

请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。

解题思路:

  • [-+]? 表示有 0 到 1 个负号或者正号
  • d* 表示有 0 到多个数字
  • (?:.d*)? 表示后面是不是紧跟着小数点和数字,(?: …)?表示一个可选的非捕获型分组。
  • (?:[eE][+-]?d+)? 表示匹配一个 e(或 E)、一个可选的正负号以及一个或多个数字。
//s字符串
function isNumeric(s) {
  // write code here
  const reg = /^[+-]?d*(.d+)?([eE][+-]?d+)?$/g;
  return reg.test(s);
}

4.字符流中第一个不重复的字符

问题描述:

请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。

如果当前字符流没有存在出现一次的字符,返回#字符。

写法一:

var str;
//Init module if you need
function Init() {
  // write code here
  str = "";
}
//Insert one char from stringstream
function Insert(ch) {
  // write code here
  str += ch;
}
//return the first appearence once char in current stringstream
function FirstAppearingOnce() {
  // write code here
  if (!str) return "#";
  var length = str.length;
  for (let i = 0; i < length; i++) {
    if (str.indexOf(str[i]) === str.lastIndexOf(str[i])) {
      return str[i];
    }
  }
  return "#";
}

写法二:

var map;
//Init module if you need
function Init() {
  // write code here
  map = {};
}
//Insert one char from stringstream
function Insert(ch) {
  // write code here
  map[ch] = map[ch] ? map[ch] + 1 : 1;
}
//return the first appearence once char in current stringstream
function FirstAppearingOnce() {
  // write code here
  for (let i in map) {
    if (map[i] === 1) {
      return i;
    }
  }
  return "#";
}
原文地址:https://www.cnblogs.com/muzidaitou/p/12699938.html