原题连接:https://leetcode.cn/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof/description/
题目:在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。。
思路:转换为char类型数组然后用两个for循环解决问题
代码:
/*
剑指 Offer 50. 第一个只出现一次的字符:
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。*/
package LeetCode;
public class offer50 {public static void main(String[] args) {char abcdefg = firstUniqChar("abaccdeff");System.out.println(abcdefg);}public static char firstUniqChar(String s) {char[] chars = s.toCharArray();for (int i = 0; i boolean flag=true;for (int j = 0; j if (i==j){continue;}if (chars[i]==chars[j]){flag=false;break ;}}if (flag==true){return chars[i];}}return ' ';}
}
/*
class Solution {public char firstUniqChar(String s) {}
}*/
思路:我们可以对字符串进行两次遍历。
在第一次遍历时,我们使用哈希映射统计出字符串中每个字符出现的次数。在第二次遍历时,我们只要遍历到了一个只出现一次的字符,那么就返回该字符,否则在遍历结束后返回空格
代码:
class Solution {public char firstUniqChar(String s) {Map frequency = new HashMap();for (int i = 0; i < s.length(); ++i) {char ch = s.charAt(i);frequency.put(ch, frequency.getOrDefault(ch, 0) + 1);}for (int i = 0; i < s.length(); ++i) {if (frequency.get(s.charAt(i)) == 1) {return s.charAt(i);}}return ' ';}
}
思路:
我们可以对方法一进行修改,使得第二次遍历的对象从字符串变为哈希映射。
具体地,对于哈希映射中的每一个键值对,键表示一个字符,值表示它的首次出现的索引(如果该字符只出现一次)或者 −1-1−1(如果该字符出现多次)。当我们第一次遍历字符串时,设当前遍历到的字符为 ccc,如果 ccc 不在哈希映射中,我们就将 ccc 与它的索引作为一个键值对加入哈希映射中,否则我们将 ccc 在哈希映射中对应的值修改为 −1-1−1。
在第一次遍历结束后,我们只需要再遍历一次哈希映射中的所有值,找出其中不为 −1-1−1 的最小值,即为第一个不重复字符的索引,然后返回该索引对应的字符。如果哈希映射中的所有值均为 −1-1−1,我们就返回空格。
代码
class Solution {public char firstUniqChar(String s) {Map position = new HashMap();int n = s.length();for (int i = 0; i < n; ++i) {char ch = s.charAt(i);if (position.containsKey(ch)) {position.put(ch, -1);} else {position.put(ch, i);}}int first = n;for (Map.Entry entry : position.entrySet()) {int pos = entry.getValue();if (pos != -1 && pos < first) {first = pos;}}return first == n ? ' ' : s.charAt(first);}
}
思路:
代码
class Solution {public char firstUniqChar(String s) {Map position = new HashMap();Queue queue = new LinkedList();int n = s.length();for (int i = 0; i < n; ++i) {char ch = s.charAt(i);if (!position.containsKey(ch)) {position.put(ch, i);queue.offer(new Pair(ch, i));} else {position.put(ch, -1);while (!queue.isEmpty() && position.get(queue.peek().ch) == -1) {queue.poll();}}}return queue.isEmpty() ? ' ' : queue.poll().ch;}class Pair {char ch;int pos;Pair(char ch, int pos) {this.ch = ch;this.pos = pos;}}
}