387:字符串中的第一个唯一字符

This commit is contained in:
huangge1199@hotmail.com 2021-07-11 23:47:11 +08:00
parent b92462a244
commit caac569267
2 changed files with 73 additions and 0 deletions

View File

@ -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<Character, Integer> 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)
}

View File

@ -0,0 +1,17 @@
<p>给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。</p>
<p>&nbsp;</p>
<p><strong>示例:</strong></p>
<pre>s = &quot;leetcode&quot;
返回 0
s = &quot;loveleetcode&quot;
返回 2
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong>你可以假定该字符串只包含小写字母。</p>
<div><div>Related Topics</div><div><li>队列</li><li>哈希表</li><li>字符串</li><li>计数</li></div></div>\n<div><li>👍 414</li><li>👎 0</li></div>