【劍指offer】- 第一個只出現一次的字符位置-34/67

1. 題目描述

在一個字符串(0<=字符串長度<=10000,全部由字母組成)中找到第一個只出現一次的字符,並返回它的位置, 如果沒有則返回 -1(需要區分大小寫).(從0開始計數)

2. 題目解析

  1. 給定一個字符串,讓你求這個字符串只出現一次的字符,我們一般的想法都是遍歷一遍字符串,依次和後面的相比較,如果一樣的話,就去掉。這裏的時間複雜度爲(On*n)
  2. 我們可以通過java中的hashmap去做,遍歷一遍字符串,判斷這個字符在不在hashmap中,如果不在,則輸入map.put(str.charAt(i), 1);如果在,則int x = map.get(str.charAt(i)); map.put(str.charAt(i), ++x);
  3. 因爲hashmap是無序的,所以我們最後需要再遍歷一遍字符串,如果當前map.get(str.charAt(i)) == 1我們直接返回i,遍歷完後,返回-1

3. 題目代碼

import java.util.HashMap;
public class Solution {
   public int FirstNotRepeatingChar(String str) {
		HashMap<Character, Integer> map = new HashMap<>();
		for (int i = 0; i < str.length(); i++) {
			if (map.containsKey(str.charAt(i))) {
				int x = map.get(str.charAt(i));
				map.put(str.charAt(i), ++x);
			} else {
				map.put(str.charAt(i), 1);
			}
		}
		for(int i = 0; i < str.length(); i++) {
			if(map.get(str.charAt(i)) == 1) {
				return i;
			}
		}
		return -1;
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章