如何找出字串中第一個不重複的字元,Java和Python的分別實現
阿新 • • 發佈:2018-11-23
遇到一個問題,網上有很多教程,在沒看的情況下,自己先寫了幾種方法,僅供參考:
Python實現方式:(三種方法,執行效率有差異)
# _*_ coding:utf-8 _*_ import time # 傳參方式 str = "=WUKVJPLKKPYBUI=JAOCFCJJIYKGNAVZPEKOLIQNEBVGILOLYOJZJUJJNEHOSJGDXQRUYGZIKCNGKKBBGLPLVHXETIZQBNTXMGTTAVRNSNRCNVZVWKFQHOSMKACKYTUQLUMALTRAFLGKYRTHKSGDOUVYWYOJITYPVPIYQIRPNWTJFYKMIGZZZYXCYIVLFXSJNE+" # str = "abcdefgadbc" # str = input("Please input a number:") # 方法一 def m1(str): list1 = [] list2 = [] for i in range(len(str)): if str[i] not in list1 and str[i] not in list2: list1.append(str[i]) else: if str[i] in list1: list2.append(str[i]) list1.remove(str[i]) else: list2.append(str[i]) print("%s\t%d" % (list1[0], str.index(list1[0]))) # 方法二 def m2(str): m = 0 list = [] for i in range(len(str)): for j in range(i + 1, len(str)): if str[i] == str[j]: m += 1 list.append(str[i]) if m == 0 and str[i] not in list: print(str[i], i) break else: m = 0 # print(str[i]) # 方法三 def m3(str): bo = [] for i in range(len(str)): bo.append(False) for i in range(len(str)): if bo[i] == False: for j in range(i + 1, len(str)): if bo[j] == False: if str[i] == str[j]: bo[i] = True bo[j] = True for k in range(len(bo)): if bo[k] == False: print("%s\t%d" % (str[k], k)) break # 統計執行時間 start = time.clock() m1(str) end = time.clock() print("Running time: %s Seconds" % (end - start)) # 方法一用時:Running time: 0.00020000000000000573 Seconds # 方法二用時:Running time: 0.0019740000000000035 Seconds # 方法三用時:Running time: 0.0005379999999999968 Seconds
Java實現方式:
public class TEST_java { public static void main(String[] args) { // System.out.println("請輸入字串:"); // Scanner sc = new Scanner(System.in); // String str = sc.nextLine(); String str = "abcdefabcdef+"; boolean[] boa = new boolean[str.length()]; int i, j, k = 0; char test, cha; for (i = 0; i < str.length(); i++) { if (boa[i] == false) { test = str.charAt(i); for (j = i + 1; j < str.length(); j++) { if (boa[j] == false) { cha = str.charAt(j); if (cha == test) { boa[i] = true; boa[j] = true; } } } } } for (k = 0; k < boa.length; k++) { if (boa[k] == false) { System.out.println(str.charAt(k) + "\t" + k); break; } } } }
《===============THE END===============》