编写一个方法,计算一个字符串中,第一个不重复的字符在当前字符串中的索引。即是这个字符串唯一一个存在的字符第一个出现的位置

1.编写一个方法,计算一个字符串中,第一个不重复的字符在当前字符串中的索引。即是这个字符串唯一一个存在的字符第一个出现的位置
比如saaaaafss 输出f saaaaaf 输出 s

public class S1 {

public static void main(String args[]){
	String aString="saaaaafss";
	int a=getIndex(aString);
	System.out.println(a);
}

public static int getIndex(String string){
	//先转成字符数组
	char c[]=string.toCharArray();
	//记录重复记录 的
	List<Character> cList=new ArrayList<Character>();
	
	for(int i=0;i<c.length;i++){
		
		if(!cList.contains(c[i])){
			//如果clist中不包含这个
			for(int j=i+1;j<c.length;j++){									
				if(c[i]==c[j]){
					//如果找到重复的 将重复的放进List中并断开
					cList.add(c[i]);
					break;
				}
				if(j==c.length-1){
					//当j已经走到最后一个数组的元素了即是数组已经
					return i;
				}
			}
			
		}
	}
	return -1;
}

}

如果有更好的解法欢迎讨论

猜你喜欢

转载自blog.csdn.net/qq_40445661/article/details/83016990