首先不重复字符

在这个JavaScript程序中,我们将编写一个接受字符串的函数,然后返回该字符串中的第一个不重复字符,例如,如果我们在该函数中输入“helloh”,我们将得到字符’e’,因为’e’在’o’之前先出现。如果该字符串中的所有字符都正在重复,那么该函数将返回一个空字符串。大写和小写字符被认为是相同的,所以’t’等于’T’!

以下是整个功能…

function firstNonRepeatingLetter(s) {
	
	let repeat = s.split("")
	let first;
	let temp = [] // we use this array to keep the character which has already been gone through before 
	let isnotrepeat = true;
	
	for(let i = 0; i < repeat.length; i++) {
		first = repeat[i];
		if(temp.includes(first))
			continue
		for(let j = i + 1; j < repeat.length; j++) {
			if(repeat[j].toLowerCase() == first.toLowerCase()) { // uppercase and lowercase character is considered to be the same 
				temp.push(first)
				isnotrepeat = false;
				break;
			}
		}
		
		if(isnotrepeat)
			return first;
		isnotrepeat = true;
	}
	
	return ""
}

如果我们在上面的函数中输入字符串“Good Morning”,我们将返回’d’。

Leave a Reply

Be the First to Comment!

avatar
  Subscribe  
Notify of