出处:http://hawstein.com/posts/1.1.html
声明:本文采用以下协议进行授权: 自由转载-非商用-非衍生-保持署名|Creative Commons BY-NC-ND 3.0 ,转载请注明作者及出处。
题目
原文:
Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures?
译文:
实现一个算法来判断一个字符串中的字符是否唯一(即没有重复).不能使用额外的数据结构。 (即只使用基本的数据结构)
解答
首先,你可以问面试官,构成字符串的字符集有多大?是ASCII字符,还是只是26个字母? 还是有更大的字符集,对于不同的情况,我们可能会有不同的解决方案。
java
package cha1; public class A001 { public static boolean isUniqueAscii(String s) { boolean aa[] = new boolean[256]; for (byte b : s.getBytes()) { if (aa[b]) return false; aa[b] = true; } return true; } public static boolean isUnique(String s) { boolean[] char_set = new boolean[256]; for (int i=0; i<s.length(); i++) { int val = s.charAt(i); if (char_set[val]) return false; char_set[val] = true; } return true; } public static void main(String[] args) { String s = "天台爱情"; System.out.println(s.length()); for (int i = 0; i<s.length(); i++) { int val = s.charAt(i); System.out.println(val + "" +s.charAt(i)); } } }
输出:
4
22825天
21488台
29233爱
24773情
C++
#include <iostream> #include <cstring> using namespace std; bool isUnique1(string s) { bool a[256]; memset(a, 0, sizeof(a)); int len = s.length(); for(int i=0; i < len; ++i) { int v = (int)s[i]; if(a[v]) return false; a[v] = true; } return true; } bool isUnique2(string s) { int a[8]; memset(a, 0, sizeof(a)); int len = s.length(); for(int i=0; i < len; ++i) { int v = (int)s[i]; int idx = v/32, shift=v%32; if(a[idx] & (1 << shift)) return false; a[idx] |= (1 << shift); } return true; } int main() { string s1 = "i am hawstein."; string s2 = "abcdefghijklmnopqrstuvwxyzABCD1234567890"; cout << isUnique1(s1) << " " << isUnique1(s2) << endl; cout << isUnique2(s1) << " " << isUnique2(s2) << endl; return 0; }