在字符串中找到第一个不重复的字符。
例:对于字符串“hellohehe”,第一个不重复的字符是“o”。
如果每个字符都有重复,则抛出运行时异常。
/**
*
* @param str string字符串
* @return char字符型
*/
function findFirstNonRepeatChar( str ) {
// write code here
const arr = str.split('')
const res = arr.filter(item => arr.indexOf(item) === arr.lastIndexOf(item))
return res.length === 0 ? new Error() : res[0]
}
module.exports = {
findFirstNonRepeatChar : findFirstNonRepeatChar
}; class Solution {
public:
/**
*
* @param str string字符串
* @return char字符型
*/
char findFirstNonRepeatChar(string str) {
// write code here
string s2;
int k=0;
double len=str.length();
for(int i=0;i<len;i++)
{
int j=0;
for(;j<len;j++)
{
if(str[i]==str[j] && i!=j)
break;
}
if (j==len)
{
s2[k++]=str[i];
}
}
return s2[0];
}
}; public char findFirstNonRepeatChar (String str) throws Exception {
// write code here
Map<Character, Integer> map = new LinkedHashMap<>();
char[] chars = str.toCharArray();
for (char c : chars) {
if(!map.containsKey(c)){
map.put(c, 1);
}else{
map.put(c, map.get(c) + 1);
}
}
Set<Map.Entry<Character, Integer>> entries = map.entrySet();
for (Map.Entry<Character, Integer> entry : entries) {
if(entry.getValue() == 1){
return entry.getKey();
}
}
throw new Exception("每个字符都有重复");
} public static Character findUnique(String str) throws Exception {
Set<Character> repeatSet = new HashSet<>();
Set<Character> uniqueSet = new ListOrderedSet();
if (StringUtils.isNotBlank(str.trim())) {
char[] chars = str.toCharArray();
for (char c : chars) {
if (!repeatSet.contains(c)) {
uniqueSet.add(c);
} else {
uniqueSet.remove(c);
}
repeatSet.add(c);
}
}
if (CollectionUtils.isEmpty(uniqueSet)) {
throw new Exception("没有独特字符,全体字符都有重复");
}
return uniqueSet.iterator().next();
}