java實現--字串中第一個單獨出現的字元
阿新 • • 發佈:2019-02-01
需求:
給定一個由大寫字母組成的字串,返回第一個單獨出現的字母
分析:
1、思路一
建立HashMap集合,遍歷字串,將各個字母及對應的角標存到集合中,再次遍歷字串,看當前字元對應的角標和HashMap集合中的角標是否相同,如果相同就直接返回,如果不同,將HashMap集合中的角標改成該字母在字串中的當前角標,繼續遍歷,如果沒有單獨出行的字母,就返回特殊標記代表沒有該字母,比如返回'#'。
2、思路二
建立HashMap集合,遍歷字串,將各個字母出現的次數記錄下來,再次遍歷字串,看map集合中該字母的個數是否是1,如果是就返回該字母,否則繼續遍歷。
3、思路三
建立int[]陣列,記錄各個字母的出現個數,大寫字母共26,所以陣列大小是26,假設A對應角標0,那麼Z對應角標25。遍歷字串,更新int[]陣列中該字元的個數,再次遍歷字串,看字元對應的個數是否是1,如果是就直接返回,否則繼續遍歷。
程式碼:
import java.util.*; class UniqueChar{ //思路一 public static char getFirstUnique1(String str){ //建立HashMap集合,將字串中各個字母和角標存到集合中 HashMap<Character, Integer> hm = new HashMap<Character, Integer>(); for(int i = 0; i < str.length(); i++){ hm.put(str.charAt(i), i); } //再次遍歷字串,看map集合中的角標和當前字元在字串中的角標是否相同,如果相同直接返回,否則修改map集合中的值,繼續遍歷 for(int i = 0; i < str.length(); i++){ if(i == hm.get(str.charAt(i))){ return str.charAt(i); } else{ hm.put(str.charAt(i), i); } } return '#'; } //思路二 public static char getFirstUnique2(String str){ //建立HashMap集合,儲存各個字母及出現的次數 HashMap<Character, Integer> hm = new HashMap<Character, Integer>(); //遍歷字串,將字母和出現的個數存到map集合中 for(int i = 0; i < str.length(); i++){ int count = 0; if(hm.containsKey(str.charAt(i))){ count = hm.get(str.charAt(i)); } hm.put(str.charAt(i), count+1); } //遍歷字串,返回出現個數是1的字母 for(int i = 0; i < str.length(); i++){ if(hm.get(str.charAt(i)) == 1){ return str.charAt(i); } } return '#'; } //思路三 public static char getFirstUnique3(String str){ //建立int[]陣列,儲存各個字母的個數 int[] result = new int[26]; //遍歷字串,更新int[]陣列中的個數 for(int i = 0; i < str.length(); i++){ result[str.charAt(i)-'A'] += 1; } //遍歷字串,返回個數是1的字母 for(int i = 0; i < str.length(); i++){ if(result[str.charAt(i)-'A'] == 1){ return str.charAt(i); } } return '#'; } public static void main(String[] args){ Scanner scan = new Scanner(System.in); String str; while(scan.hasNext()){ str = scan.nextLine(); System.out.println(str+"字串中第一個單獨出現的字母是"+getFirstUnique1(str)); System.out.println(str+"字串中第一個單獨出現的字母是"+getFirstUnique2(str)); System.out.println(str+"字串中第一個單獨出現的字母是"+getFirstUnique3(str)); } } }