*************
C++
topic: 面试题 01.01. 判定字符是否唯一 - 力扣(LeetCode)
*************
Have too much works recently. The hard ones take me lot if time insteed. I need to do easy ones to save some time for daily work. If extra time comes, I will recal the hard ones.
Inspect the topic:

The purpose of the topic is finding the element comes twice or more in the given string. Check, find a element in a string, I do remind the HASH table.
IN C++, hashtable is a standard library, the standard usage of hash comes as follow:
#include <unordered_map> // this is the head file
// state hash table
unordered_map<KeyType, ValueType> hashTable;
// insert elements
hashTable[key] = value;
// visit elements
ValueType value = hashTable[key];
// check the value exist or not
if (hashTable.find(key) != hashTable.end()) {
};
// delete elements
hashTable.erase(key);
// visit hashTable
for (auto& pair : hashTable);
In this topic, find function is about to choosed to facilitate the solution.
Inspect the logic of find code:
// check the value exist or not
if (hashTable.find(key) != hashTable.end()) {
};
Once the element has been found, the pointer moves next;
once not, it returns end(); Pay special attention here end() means a logo, tell ya the failure of finding. I can make command in {}.
For instance:
unordered_map<int, string> umap;
// 假设umap中没有元素1
auto it = umap.find(1);
if (it != umap.end()) {
// 元素存在
} else {
// 元素不存在
}
One of my confusion is the return of the find. The return value of the find method is an iterator, not a boolean.
Simulate the prigress:
string astr = abcde
- ‘a’ is not in the set, insert set, set now has ‘a’
- ‘b’ is not in set, insert set, set now has ‘a’,‘b’
- ‘c’ is not in set, insert set, set now has ‘a’,‘b’,‘c’
- ‘d’ is not in set, insert set, set now has ‘a’,‘b’,‘c’,‘d’
- ‘e’ is not in set, insert set, set now has ‘a’,‘b’,‘c’,‘d’,‘e’
It works,
so let's write the code:
make the unorder_set
class Solution {
public:
bool isUnique(string astr) {
unordered_set<char> charSet;
}
};
visit the astr:
class Solution {
public:
bool isUnique(string astr) {
unordered_set<char> charSet;
// visit astr
for (char c : astr) {
}
};
use find:
class Solution {
public:
bool isUnique(string astr) {
unordered_set<char> charSet;
// visit astr
for (char c : astr) {
// find
if (charSet.find(c) != charSet.end()) {
return false;
}
// insert
charSet.insert(c);
}
return true;
}
};
and it works:


2832

被折叠的 条评论
为什么被折叠?



