剑指offer (34)

题目 : 在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).

思路 :
1.遍历str,把字符存进一个数组中,数组下标和字符ASCII码相关 ,值代表频次。
2.再遍历一遍str,去数组中查找相对应的频次如何,如果=1,则返回,此时就是第一个只出现一次的字符。

	public int FirstNotRepeatingChar(String str) {
		// a-z:65~90 A-Z:97 ~122 所以a~Z:共65位
		int[] arr = new int[65];
		for (int i = 0; i < str.length(); i++) {
			int index = (int) str.charAt(i) - 65;
			if (arr[index] == 0) {
				arr[index] = 1;
			} else {
				arr[index]++;
			}
		}
		for (int j = 0; j < str.length(); j++) {
			int index = (int) str.charAt(j) - 65;
			if (arr[index] == 1) {
				return j;
			}
		}
		return -1;
	}
发布了50 篇原创文章 · 获赞 0 · 访问量 394

猜你喜欢

转载自blog.csdn.net/weixin_46108108/article/details/104202589