网站页面如何设计图/软文营销的写作技巧有哪些
字符串中的第一个唯一字符
- 题目描述
- 解题历程
- 第一次(超时)
- 第二次
- 第三次
- 第四次
- 总结
题目描述
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例:
s = "leetcode"
返回 0
s = "loveleetcode"
返回 2
解题历程
第一次(超时)
class Solution {public int firstUniqChar(String s) {char [] ch = s.toCharArray();int [] num =new int[ch.length];
if(ch.length==1)return 0;for(int i=0;i<ch.length-1;i++){for(int j=i+1;j<ch.length;j++){if(ch[i] ==ch[j]){num[i]++;num[j]++;
}
}if(num[i]==0){//没有记过数//System.out.print(ch[i]);return i;}}if(num[ch.length-1] == 0){// System.out.print(ch[i]);return ch.length-1;}return -1;}
}
第二次
public static void main(String[] args) {// 定义字符串String string = "fdafasfsfasf"; // 定义map容器Map<Character, Integer> map = new HashMap<Character, Integer>();for (int i = 1; i < string.length(); i++) { char ch = string.charAt(i); if (map.containsKey(ch)) {int count = map.get(ch);count = count + 1;map.put(ch, count);} else {map.put(ch, 1);}}// 遍历map集合Set<Character> keySet = map.keySet();for (Character chars : keySet) {System.out.println("字符:"+chars + ",出现的次数为:"+map.get(chars));} }
第三次
采用map 能返回数量为一的值,但是无法保证顺序,即有多个不重复字符时,可能出错。
class Solution {public int firstUniqChar(String s) {// 定义map容器Map<Character, Integer> map = new HashMap<Character, Integer>();for (int i = 0; i < s.length(); i++) {char ch = s.charAt(i);if (map.containsKey(ch)) {int count = map.get(ch);count = count + 1;map.put(ch, count);} else {map.put(ch, 1);}}// 遍历map集合Set<Character> keySet = map.keySet();for (Character chars : keySet) {int t = map.get(chars);if(t==1){System.out.print(chars);return 0;}}return -1;}
第四次
不是map不可以得到结果,而是要采用合适的方法。
class Solution {public int firstUniqChar(String s) {Map<Character,Integer> map =new HashMap<Character,Integer>();
int n = s.length();
//第一次遍历 放入map
for(int i=0;i<n;i++){char ch = s.charAt(i);//存入对应的个数map.put(ch,map.getOrDefault(ch,0)+1);
}
//第二次遍历 返回第一个为一的字符
for(int i=0;i<n;i++){
if(map.get(s.charAt(i))==1)return i;
}return -1;}
}
总结
-
getOrDefault(ch,index) 方法,存在ch返回该值,不存在返回指定默认值index
-
s.charAt(i) 返回该位置对应的字符
-
Map
(1)建立map
Map<Character,Integer> map =new HashMap<Character,Integer>();
(2)map放入数据
map.put(ch,map.getOrDefault(ch,0)+1);
(3)map拿key对应的value值
map.get(s.charAt(i))
(4)遍历map
Set<Character> keySet = map.keySet(); for (Character chars : keySet) {...}
(5)判断key在map中是否有key存在
map.containsKey(ch)