//方法1
//这种方法只适用于目标字符长度为1的情况
function foundStr(str){
var arrResult=null;
if(typeof str === 'string'){
for(let i of str){
if(str.indexOf(i) == str.lastIndexOf(i)){
arrResult = i;
break;
}
}
if(arrResult!=null){
console.log("result:",arrResult);
}
else{
console.log("没有符合的字符");
}
}
else{
console.log('传入的不是字符串');
}
}
var str = 'cbaacfdeaebb';
foundStr(str)
// 方法2
function foundStr2(str) {
console.time()
var obj = {}
var objLen = 0
var minNum = Infinity
var arrResult = null
if (typeof str === 'string') {
for (var i of str) {
// 字符被按照出现顺序放入
if (!obj[i]) {
obj[i] = 1
objLen++
} else {
obj[i]++
}
}
console.log(obj);
//遍历得到最小值
for (var i in obj) {
if (obj[i] < minNum) {
minNum = obj[i]
arrResult = i
}
}
if (arrResult != null) {
console.log("result:", arrResult);
} else {
console.log("没有符合的字符");
}
} else {
console.log('传入的不是字符串');
}
console.timeEnd()
}
var str = '123412341234123412341234123412341234123412341234123412341234123412341234123412341234bacabc';
foundStr2(str)//b
如有考虑不周的地方还请提出指正!