一、題目介紹
實現一個算法,確定一個字符串 s 的所有字符是否全都不同。
示例 1:
輸入: s = "leetcode"
輸出: false
示例 2:
輸入: s = "abc"
輸出: true
限制:
0 <= len(s) <= 100
如果你不使用額外的數據結構,會很加分。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/is-unique-lcci
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
二、解題思路
本題如果用set的數據結構很容易實現,這裏不做介紹。按照限制的要求,不適用額外的數據結構。因爲輸入的字符串全都由小寫字母組成,這裏構建長度爲26的字符數組來記錄每個字符是否出現過。具體實現詳見代碼。
三、解題代碼
class Solution {
public:
bool isUnique(string astr) {
char s[26] = {0};
for(int i = 0; i < astr.size(); ++i)
{
if(s[astr[i] - 'a'] == 1)
return false;
s[astr[i] - 'a'] = 1;
}
return true;
}
};