diff --git a/src/main/java/leetcode/editor/cn/FirstUniqueCharacterInAString.java b/src/main/java/leetcode/editor/cn/FirstUniqueCharacterInAString.java new file mode 100644 index 0000000..d2e0685 --- /dev/null +++ b/src/main/java/leetcode/editor/cn/FirstUniqueCharacterInAString.java @@ -0,0 +1,56 @@ +//给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 +// +// +// +// 示例: +// +// s = "leetcode" +//返回 0 +// +//s = "loveleetcode" +//返回 2 +// +// +// +// +// 提示:你可以假定该字符串只包含小写字母。 +// Related Topics 队列 哈希表 字符串 计数 +// 👍 414 👎 0 + +package leetcode.editor.cn; + +import java.util.HashMap; +import java.util.Map; + +//387:字符串中的第一个唯一字符 +class FirstUniqueCharacterInAString{ + public static void main(String[] args) { + //测试代码 + Solution solution = new FirstUniqueCharacterInAString().new Solution(); + } + //力扣代码 + //leetcode submit region begin(Prohibit modification and deletion) +class Solution { + public int firstUniqChar(String s) { +// for (int i = 0; i < s.length(); i++) { +// if(!s.substring(i+1).contains(""+s.charAt(i))&&!s.substring(0,i).contains(""+s.charAt(i))){ +// return i; +// } +// } +// return -1; + Map map = new HashMap<>(); + for (int i = 0; i < s.length(); ++i) { + char ch = s.charAt(i); + map.put(ch, map.getOrDefault(ch, 0) + 1); + } + for (int i = 0; i < s.length(); ++i) { + if (map.get(s.charAt(i)) == 1) { + return i; + } + } + return -1; + } +} +//leetcode submit region end(Prohibit modification and deletion) + +} \ No newline at end of file diff --git a/src/main/java/leetcode/editor/cn/FirstUniqueCharacterInAString.md b/src/main/java/leetcode/editor/cn/FirstUniqueCharacterInAString.md new file mode 100644 index 0000000..ce3760f --- /dev/null +++ b/src/main/java/leetcode/editor/cn/FirstUniqueCharacterInAString.md @@ -0,0 +1,17 @@ +

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

+ +

 

+ +

示例:

+ +
s = "leetcode"
+返回 0
+
+s = "loveleetcode"
+返回 2
+
+ +

 

+ +

提示:你可以假定该字符串只包含小写字母。

+
Related Topics
  • 队列
  • 哈希表
  • 字符串
  • 计数
  • \n
  • 👍 414
  • 👎 0
  • \ No newline at end of file