法1:使用HashMap
Python
class Solution:
def dismantlingAction(self, arr: str) -> str:
res = ' '
count_map = Counter(list(arr))
for item in arr:
if count_map[item] == 1:
res = item
break
return res
Java
class Solution {
public char dismantlingAction(String arr) {
if (arr.length() == 0) {
return ' ';
}
char[] array = arr.toCharArray();
Map<Character, Integer> charToCountMap = new HashMap<>();
for (char c : array) {
int origin = charToCountMap.getOrDefault(c, 0);
charToCountMap.put(c, origin + 1);
}
for (char c : array) {
if (charToCountMap.get(c) == 1) {
return c;
}
}
return ' ';
}
}
法2:AscII码值
class Solution {
public char dismantlingAction(String arr) {
if (arr.length() == 0) {
return ' ';
}
int[] count = new int[256];
char[] array = arr.toCharArray();
for (char c : array) {
count[c] += 1;
}
for (char c : array) {
if (count[c] == 1) {
return c;
}
}
return ' ';
}
}
##Solution1:
垃圾算法不看也罢!自己想到的垃圾算法
class Solution {
public:
int FirstNotRepeatingChar(string str) {
if(str.size() == 0)
return -1;// -1值是提交一遍试错试出来的
else {
map<char,int> res;
for(int i = 0; i < str.size(); i++){
if(res.find(str[i]) == res.end()) //注意在map中若找不到关键字则返回尾迭代器
res[str[i]] = 1;
else
res[str[i]]++;
}
int temp_begin = 0, first_begin = INT_MAX;
for(auto iter = res.begin(); iter != res.end(); iter++)
if(iter->second == 1){
temp_begin = str.find_first_of(iter->first);
first_begin = min(temp_begin,first_begin);
}
return first_begin;
}
}
};
##Solution2:
还是利用哈希的思想,啊~
参考网址:https://www.nowcoder.com/profile/826671/codeBookDetail?submissionId=14914215
代码如此简化的原因是:字符本质上就是数字啊,字符的ASCII码值范围是从0到255共256个字符。
class Solution {
public:
int FirstNotRepeatingChar(string str) {
if(!str.size()) return -1;
char ch[256] = { 0 };
for (int i = 0; i < str.size(); i++)
ch[str[i]]++;
for(int i = 0; i < str.size(); i++)
if(ch[str[i]] == 1)
return i;
return 0;
}
};