hash 的经典 ,也不慢 , hoperun的异类 ,速度随使用字符集的总数而变, 如果字符串长度为100K,总使用字符数(如中文信息)为3K,(普通文章而已) 那么计算总量为 a(常数) * 3 k* 100 k = 300 M * a (3 k 次遍历) hash 为 b * 100K (一次遍历)
to hoperun: 比如用当前网页的源码,作为字符串就知道速度了
我也来写一个可能比较耗内存的: public static void main(String[] args) throws Exception { // int[] c = new int['\uffff'];//针对所有字符 int[] c = new int[256]; //只考虑 ascii String s = "aabbabcca"; int len = s.length(); for (int i = 0; i < len; i++) { c[s.charAt(i)]++; } for (int i = 0; i < c.length; i++) { if (c[i] > 0) { System.out.print( (char) i); System.out.println(c[i]); } } }
String str = "aabbccddee";
char[] array = str.toCharArray();
String result = "";
int length = array.length - 1;
char element = array[length];
while (true) {
int tempCount = 0;
if (element != ' ') {
for (int i = length; i >= 0; i--) {
if (element == array[i]) {
tempCount++;
array[i] = ' ';
}
}
result = element + "" + tempCount + result;
element = array[length];
} else {
--length;
if (length < 0) {
break;
}
element = array[length];
continue;
}
}
System.out.println(result);
}
然后根据字符去map中找,不空,就加1,空就赋值1
private static void test8() {
String str = "aabbabcca";
char[] array = str.toCharArray();
String result = "";
int length = array.length - 1;
int loop = 0;
char element = array[loop];
while (true) {
int tempCount = 0;
if (element != ' ') {
for (int i = 0; i <= length; i++) {
if (element == array[i]) {
tempCount++;
array[i] = ' ';
}
}
result = result + ""+ element + "" + tempCount; element = array[loop];
} else {
++loop;
if (loop > length) {
break;
}
element = array[loop];
continue;
}
}
System.out.println(result);
}--------------------------------------------
前期资本积累,记得给分哦
ArrayList<Character> a=new ArrayList<Character>();
Hashtable<Character,Integer> h=new Hashtable<Character,Integer>();
for(int i=0;i<s.length();i++)
{
char c=s.charAt(i);
if(!h.containsKey(c))
{
a.add(c);
h.put(c,1);
}
else
h.put(c,h.get(c)+1);
}
StringBuffer sb=new StringBuffer();
for(char c:a)
{
sb.append(c);
sb.append(h.get(c));
}
System.out.println(sb.toString());
,速度随使用字符集的总数而变, 如果字符串长度为100K,总使用字符数(如中文信息)为3K,(普通文章而已)
那么计算总量为 a(常数) * 3 k* 100 k = 300 M * a
(3 k 次遍历)
hash 为 b * 100K (一次遍历)
比如用当前网页的源码,作为字符串就知道速度了
// int[] c = new int['\uffff'];//针对所有字符
int[] c = new int[256]; //只考虑 ascii
String s = "aabbabcca";
int len = s.length();
for (int i = 0; i < len; i++) {
c[s.charAt(i)]++;
}
for (int i = 0; i < c.length; i++) {
if (c[i] > 0) {
System.out.print( (char) i);
System.out.println(c[i]);
}
}
}
static void Kaesar(String c,int n)
{
char[] s=c.toCharArray();
char[] mi=new char[s.length];
int[] miNum=new int[s.length];
for(int i=0;i<c.length();i++)
{
miNum[i]=(int)(s[i]-'a');
mi[i]=(char)((miNum[i]+n)%26+97);
System.out.print(mi[i]);
}
System.out.println();
}
public static void main(String[] args)
{
String s="aabbabcca";
Au.Kaesar(s,256);
}}