劍指offer——(15)第一個只出現一次的字元 && 陣列中重複的數字 && 字元流中第一個不重複的字元
阿新 • • 發佈:2018-11-30
public class Solution { public int FirstNotRepeatingChar(String str) { if(str.length()<=0) return -1; char c[] = str.toCharArray(); char zimu[] = new char['z']; // ASCII碼中對應的十進位制數是122 //System.out.println(zimu.length); for(int ch:c) zimu[ch-1]++; // 儲存字串中每個字元出現的次數 int count = 0; for(;count<str.length();count++){ if(zimu[c[count]-1]==1) break; // 只出現一次的字元 } if(count==str.length()-1) return -1; return count; } }
public class Solution { // Parameters: // numbers: an array of integers // length: the length of array numbers // duplication: (Output) the duplicated number in the array number,length of duplication array is 1,so using duplication[0] = ? in implementation; // Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++ // 這裡要特別注意~返回任意重複的一個,賦值duplication[0] // Return value: true if the input is valid, and there are some duplications in the array number // otherwise false public boolean duplicate(int numbers[],int length,int [] duplication) { int temp[] = new int[length]; boolean boo = false; for(int i=0;i<length;i++){ temp[numbers[i]]++; } for(int i=0;i<length;i++){ if(temp[numbers[i]]>1) { duplication[0] = numbers[i]; //第一個出現次數兩次及兩次以上的數字 boo = true; break; } } return boo; } }
public class Solution { int zimu[] = new int['z']; int length; StringBuilder str = new StringBuilder(); //Insert one char from stringstream public void Insert(char ch) { str.append(ch); int k = ch-1; zimu[k]++; } //return the first appearence once char in current stringstream public char FirstAppearingOnce() { char temp[] = new char[str.length()]; char result = ' '; for(int i=0;i<str.length();i++){ temp[i] = str.charAt(i); } int count = 0; for(;count<temp.length;count++){ if(zimu[temp[count]-1]==1){ result = temp[count]; break; } } if(count==temp.length) result = '#'; System.out.println(result); return result; } }