【leetcode】字符串中的第一个唯一的字符

题目要求

  • 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引,如果不存在,则返回-1;
  • 案例:
    s = “leetcode”
    返回 0.
    s = “loveleetcode”
    返回 2.
  • 注意事项:可以假定该字符串只包含小写字母

核心思想

很简单的思路,就是用字符串来遍历查找。这个在做的过程有一个小错误,就是没有定义int[26]的数组,这样在验证字符串类似"aaabba"时就会产生返回值错误,后来又查看了别人博客得到的解答。另外还可用hashmap来做。

完整代码如下

/**
 * 题目:字符串中第一个唯一的字符
 * 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引,如果不存在,则返回-1;
 * 案例:
 * s = "leetcode"
 * 返回 0.
 * s = "loveleetcode"
 * 返回 2.
 * 注意事项:可以假定该字符串只包含小写字母
 *
 */
public class Solution {
	public static int FirstUniqChar(String s) {
	   	int[] a = new int[26];
	    char[] ch = s.toCharArray();
	    for(int i = 0; i < s.length(); i++) {
	      a[(int)(ch[i]-'a')]++;
	    }
	    for(int i = 0; i < s.length(); i++) {
	      if(a[(int)(ch[i]-'a')] == 1)
	       return i;
	    }
	    return -1;
	}
	public static void main(String[] args) {
		
		System.out.println(Solution.FirstUniqChar("leetcode"));
		System.out.println(Solution.FirstUniqChar("loveleetcode"));

	}
}


猜你喜欢

转载自blog.csdn.net/weixin_42967016/article/details/85074867
今日推荐