-
Notifications
You must be signed in to change notification settings - Fork 634
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
剑指Offer:第一个只出现一次的字符 #50
Comments
var firstUniqChar = function(s) {
let map = new Map()
let queue = []
for (let i = 0; i < s.length; i++) {
let c = s[i]
if(map.has(c)) {
let count = queue[map.get(c)][1]
queue[map.get(c)][1] += 1
} else {
map.set(c, queue.length)
queue.push([c, 1])
}
}
let res = queue.filter(item => item[1] === 1)
return res.length ? res.shift()[0] : ' '
}; 复杂度分析:
|
|
/**
* @param {string} s
* @return {character}
*/
var firstUniqChar = function(s) {
var map = new Map();
for (var i = 0; i < s.length; i++) {
var subStr = s[i];
if (map.get(subStr)) {
map.set(subStr, 2);
} else {
map.set(subStr, 1);
}
}
console.log(map)
for (var key of map.keys()) {
if (map.get(key) === 1) {
return key;
}
}
return ' ';
}; |
解答:使用Map使用
const firstUniqChar = function(s) {
if(!s) return " "
let map = new Map()
for(let c of s) {
if(map.has(c)) {
map.set(c, map.get(c) + 1)
} else {
map.set(c, 1)
}
}
for(let c of map.keys()) {
if(map.get(c) === 1) {
return c
}
}
return " "
}; 复杂度分析:
|
if(!s.trim()) return " "; |
不需要遍历两次。 /*
|
`javascript function firstString(str) {
|
|
想了很久,还是做了两次遍历,使用 const firstUniqChar = (source: string) => {
if (source.length <= 0) return ' ';
const mapValueToIndex: Record<string, number> = {};
const charList: (string | undefined)[] = [];
for (let i = 0; i < source.length; i++) {
const char = source.charAt(i);
const index = mapValueToIndex[char];
if (index !== undefined) {
delete mapValueToIndex[char];
charList[index] = undefined;
continue;
}
mapValueToIndex[char] = i;
charList[i] = char;
}
for (let j = 0; j < charList.length; j++) {
if (charList[j] !== undefined) {
return charList[j];
}
}
return ' ';
};
console.log(firstUniqChar('abaccdeff'));
console.log(firstUniqChar('adbaccdeff'));
console.log(firstUniqChar(''));
// 输出
// b
// b
// ' ' |
static firstUniqChar(s) {
|
在字符串
s
中找出第一个只出现一次的字符。如果没有,返回一个单空格。s
只包含小写字母。示例:
限制:
0 <= s 的长度 <= 50000
附赠leetcode地址:leetcode
The text was updated successfully, but these errors were encountered: