栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Java

0020力扣387题---字符串中的第一个唯一字符

Java 更新时间:发布时间: 百科书网 趣学号

力扣387题---字符串中的第一个唯一字符

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

 示例 1:输入: s = "leetcode"  输出: 0
示例 2: 输入: s = "loveleetcode"  输出: 2
示例 3: 输入: s = "aabb"  输出: -1
 

提示:

1 <= s.length <= 10^5
s只包含小写字母


方法1:使用Java的api

    public int firstUniqChar(String s) {
        for (int i = 0; i < s.length(); i++) {
            if (s.indexOf(s.charAt(i)) == s.lastIndexOf(s.charAt(i))) {
                return i;
            }
        }
        return -1;
    }

测试:

public class Main {
    public static void main(String[] args) {
        String str = "leetcode";
        Main solution = new Main();
        System.out.println(solution.firstUniqChar(str));
    }

    public int firstUniqChar(String s) {
        for (int i = 0; i < s.length(); i++) {
            if (s.indexOf(s.charAt(i)) == s.lastIndexOf(s.charAt(i))) {
                return i;
            }
        }
        return -1;
    }
}


输出:0


方法2:两次遍历法

第一遍先统计每个字符出现的次数,第二遍再次从前往后遍历字符串s中的每个字符,如果某个字符出现一次直接返回

    public int firstUniqChar(String s) {
        int[] array = new int[26];
        char[] chars = s.toCharArray();
        for (int i = 0; i < s.length(); i++)
            array[chars[i] - 'a']++;
        for (int i = 0; i < s.length(); i++) {
            if (array[chars[i] - 'a'] == 1) {
                return i;
            }
        }
        return -1;
    }

测试:

public class Main {
    public static void main(String[] args) {
        String str = "loveleetcode";
        Main solution = new Main();
        System.out.println(solution.firstUniqChar(str));
    }

    public int firstUniqChar(String s) {
        int[] array = new int[26];
        char[] chars = s.toCharArray();
        //先统计每个字符出现的次数
        for (int i = 0; i < s.length(); i++)
            array[chars[i] - 'a']++;
        //然后在遍历字符串s中的字符,如果出现次数是1就直接返回
        for (int i = 0; i < s.length(); i++) {
            if (array[chars[i] - 'a'] == 1) {
                return i;
            }
        }
        return -1;
    }
}


输出:2
 

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/986351.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号