1. Topic introduction
Implement an algorithm to determine whether all characters of a string s are all different.
Example 1:
Input: s = "leetcode"
Output: false
Example 2:
Input: s = "abc"
Output: true
Limit:
0 <= len(s) <= 100
If you don't use additional data structures, it will be a bonus.
Source: LeetCode
Link: https://leetcode-cn.com/problems/is-unique-lcci
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Two, problem-solving ideas
This question is easy to implement if the data structure of set is used, so I won't introduce it here. According to restrictions, no additional data structure is applicable. Because the input string consists of all lowercase letters, a character array with a length of 26 is constructed here to record whether each character has appeared. See the code for specific implementation.
Three, problem-solving code
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;
}
};