首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

今日面试了,关于字符串截取的

2013-07-04 
今天面试了,关于字符串截取的有一个数组,String [] a{ads,awww,fdgfdf,fvdsfc,hyjutfrdf},题目要求,例如,

今天面试了,关于字符串截取的
有一个数组,String [] a={ads,awww,fdgfdf,fvdsfc,hyjutfrdf},
题目要求,例如,数组a={ads}中,在a-z共二十六个字母中,字母a出现了1次,d出现了1次,s出现了1次,其他字母出现了0次,求出在以上数组中,打印出各个字母都出现了多少次。
呵呵,求高人给大家解答分享下。
[解决办法]
利用ascii码值的范围很小[0, 255],直接定义一个大小为256的数组,这样解决办法可以简化很多。

public class Hello {
    public static void main(String[] args) {
        String [] a = {"ads", "awww", "fdgfdf", "fvdsfc", "hyjutfrdf"};
        int[] frequence = new int[256];

        for (String str : a) {
            for (int i = 0; i < str.length(); ++i) {
                frequence[str.charAt(i)]++;
            }
        }

        for (int i = 0; i < frequence.length; ++i) {
            if (frequence[i] != 0) {
                System.out.printf("%s: %d\n", (char)i, frequence[i]);
            }
        }
    }
}

a: 2
c: 1
d: 5
f: 7
g: 1
h: 1
j: 1
r: 1
s: 2
t: 1
u: 1
v: 1
w: 3
y: 1

[解决办法]
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class StringCount
{
public static void main(String[] args)
{

String[] arr ={"ads","awww","fdgfdf","fdgfdf","fdgfdf"};



System.out.println(getCount(arr));;
}

private static String getCount(String[] strs)
{
StringBuilder builder = new StringBuilder();
for(int x=0; x<strs.length; x++)
{
builder.append(strs[x]);
}

String s = builder.toString();

char[] arr = s.toCharArray();

Map<Character,Integer> map = new TreeMap<Character,Integer>();
int count = 1;

for(int x=0; x<arr.length; x++)
{
if(!(arr[x]>='a' && arr[x]<='z' 
[解决办法]
 arr[x]>='A' && arr[x]<='Z'))
continue;

if(!(map.containsKey(arr[x])))
map.put(arr[x], count);
else
count = map.get(arr[x]) + 1;
map.put(arr[x], count);
count = 1;
}

StringBuilder sb = new StringBuilder();

Iterator<Map.Entry<Character, Integer>> it = map.entrySet().iterator();

while(it.hasNext())
{
Map.Entry<Character, Integer> me = it.next();
char key = me.getKey();
int value =  me.getValue();

sb.append(key+":("+value+")");
}
return sb.toString();
}
}


[解决办法]
public class times {

/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] s = {"ads","awww","fdgfdf","fvdsfc","hyjutfrdf"};
int[] len = new int[26];
for(int i = 0;i < s.length;i++){
for(int j = 0;j <s[i].length();j++){
len[s[i].charAt(j) - 'a']++;
}
}
for(int i = 0;i < 26;i++){
char temp;
temp = (char)('a' + i);
System.out.print(temp);
System.out.println(":"+len[i]);
}

}

}

热点排行