LeetCode第387题

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

思路:主要检测运用String类的方法的熟练程度。

1.将字符串转化为字符数组

2.遍历字符数组,对取到的每一个字符进行比较,如果这个字符出现的第一个索引的位置和最后一次出现的索引的位置一样的话,则返回索引。否则返回-1.

public static int firstUniqChar(String s){
		char[] ss=s.toCharArray();
		for(int i=0;i<ss.length;i++){
			char a=s.charAt(i);
			if(s.indexOf(a)==s.lastIndexOf(a)){
				return i;
			}
		}
		return -1;
	}

猜你喜欢

转载自blog.csdn.net/qq_37764098/article/details/84715749