Vấn đề
Chúng ta cần thiết kế một cấu trúc dữ liệu trong JavaScript hỗ trợ hai thao tác:
addWord, thêm từ vào Cấu trúc Dữ liệu (DS), có thể dùng mảng hoặc DS hiện có để lưu trữ,search, tìm một từ chữ nghĩa hoặc chuỗi biểu thức chính quy chứa chữ thường "a-z" hoặc "." trong đó "." đại diện cho bất kỳ chữ cái nào.
Ví dụ:
addWord("sir")
addWord("car")
addWord("mad")
search("hell") === false
search(".ad") === true
search("s..") === trueVí dụ
Dưới đây là mã nguồn:
class MyData{
constructor(){
this.arr = [];
};
};
MyData.prototype.addWord = function (word) {
this.arr.push(word)
};
MyData.prototype.search = function (word) {
let reg = new RegExp('^'+word+'$');
return !!this.arr.find(el => reg.test(el));
};
const data = new MyData();
data.addWord('sir');
data.addWord('car');
data.addWord('mad');
console.log(data.search('hell'));
console.log(data.search('.ad'));
console.log(data.search('s..'));Kết quả
Kết quả đầu ra trong console:
false true true