LeetCode387 字符串中的第一个唯一字符 & 剑指Offer 50 第一个只出现一次的字符
题目
LeetCode387 字符串中的第一个唯一字符:
剑指Offer 50 第一个只出现一次的字符:
387题返回的是字符,剑指Offer 50返回的是索引。
解题
解题一:使用哈希表存储频数
剑指Offer 50 第一个只出现一次的字符:
// javascript
var firstUniqChar = function(s) {
const frequency = _.countBy(s);
for (const [i, ch] of Array.from(s).entries()) {
if (frequency[ch] === 1) {
return ch;
}
}
return ' ';
};
LeetCode387 字符串中的第一个唯一字符:
// javascript
var firstUniqChar = function(s) {
const frequency = _.countBy(s);
for (const [i, ch] of Array.from(s).entries()) {
if (frequency[ch] === 1) {
return i;
}
}
return -1;
};
解题二:使用哈希表存储索引
// javascript
var firstUniqChar = function(s) {
const n = s.length;
const position = new Map();
for (const [i, ch] of Array.from(s).entries()) {
if (position.has(ch)) {
position.set(ch, -1);
} else {
position.set(ch, i);
}
}
let first = n;
for (const pos of position.values()) {
if (pos !== -1 && pos < first) {
first = pos;
}
}
return first === n ? ' ' : s[first];
// return first === n ? -1 : first;// 387题返回值
};
解题三:队列
// javascript
var firstUniqChar = function(s) {
const position = new Map();
const queue = [];
for (const [i, ch] of Array.from(s).entries()) {
if (!position.has(ch)) {
position.set(ch, i);
queue.push([ch, i]);
} else {
position.set(ch, -1);
while (queue.length > 0 && position.get(queue[0][0]) === -1) {
queue.shift();
}
}
}
return queue.length > 0 ? queue[0][0] : ' ';
// return queue.length > 0 ? queue[0][1] : -1; // 387题返回值
};