面试题 01.01: 判定字符是否唯一(C++)

题目地址:https://leetcode-cn.com/problems/is-unique-lcci/

题目描述

实现一个算法,确定一个字符串 s 的所有字符是否全都不同。

题目示例

示例 1:

输入: s = "leetcode"
输出: false
示例 2:

输入: s = "abc"
输出: true
限制:

0 <= len(s) <= 100

解题思路

思路1:暴力破解。这道题目很简单,重要的是进行优化,我们可以双层遍历判断是否字符串中有重复的字符出现,若出现,则返回false即可。

思路2:又看到了统计字符个数,直接上手map,遍历字符串使用map存储每个字符出现的次数,最后判断map中存储的每个字符是否出现的次数超过1次,如果出现,则直接返回false。

程序源码

思路1

class Solution {
public:
    bool isUnique(string astr) {
        if(astr.size() == 0) return true;
        for(int i = 0; i < astr.size(); i++)
        {
            for(int j = i + 1; j < astr.size(); j++)
            {
                if(astr[i] == astr[j]) return false;
            }
        }
    }
};

思路2

class Solution {
public:
    bool isUnique(string astr) {
        if(astr.size() == 0) return true;
        unordered_map<char, int> mp;
        for(int i = 0; i < astr.size(); i++)
        {
            mp[astr[i]]++;
        }
        for(int j = 0; j < mp.size(); j++)
        {
            if(mp[astr[j]] > 1) return false;
        }
        return true;
    }
};

猜你喜欢

转载自www.cnblogs.com/wzw0625/p/12899535.html