哈希表 - 判定字符是否唯一 -简单

*************

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:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值