2015-10-02 103 views
1

我在采访中得到了一个java问题。在字符串中打印不同的字符,并在每个字符下面打印星号(*),以显示该字符串中字符重复的次数。打印星号(*)在字符串中的字符在java

对于例如:我的字符串是“GOOGLE”,那么输出应该是

G O L E 
* * * * 
* * 

我在java中试过,我能创造一个HashMap,将重复的字符和数字存储的字符串中。但是HashMap不是基于字符串的插入顺序。我也不知道我的下一步应该是什么。有人能帮我吗?在此先感谢

public void myFunction(String str) { 
    int length = str.length(); 
    HashMap<Character, Integer> hm = new HashMap<>(); 
    for(int i=0;i<length;i++){ 
     char ch = str.charAt(i); 
     if(hm.containsKey(ch)){ 
      hm.put(ch, hm.get(ch)+1);    
     } 
     else { 
      hm.put(ch, 1); 
     } 


    } 
     System.out.println(hm); 
} 

OUTPUT - Enter a String: 
GOOGLE 
{E=1, G=2, L=1, O=2} 
+0

你可以找到答案在这里:http://stackoverflow.com/questions/683518/java-class-that-implements-map-and-keeps-insertion-order 检查尤其是LinkedHashMap的 – VLef

+0

有没有需要使用HashMap来做这样简单的事情。这是相关的,但是矫枉过正。具有3行代码的简单1D阵列可以实现。 – user3437460

回答

2

如果您使用LinkedHashMap它将保持插入的顺序。你可以做这样的事情。还要添加一个max变量,因为我们稍后会在打印时需要它。

String input = "GOOGLE"; 
int max = 0; 
LinkedHashMap<Character, Integer> map = new LinkedHashMap<>(); 
for (char c: input.toCharArray()){ 
    if (map.containsKey(c)){ 
     map.put(c, map.get(c) + 1); 
    }else{ 
     map.put(c, 1); 
    } 
    max = Math.max(max, map.get(c)); 
} 
System.out.println(map); 

输出:

{G=2, O=2, L=1, E=1} 

然后,只需遍历你有多少行打印,并通过每个字符迭代。像这样的东西应该可以做到。

for (int i=0; i<=max; i++){ 
    for (char c: map.keySet()){ 
     if (i==0){ 
      System.out.print(c); 
     }else if (i<= map.get(c)){ 
      System.out.print("*"); 
     }else{ 
      System.out.print(" "); 
     } 
    } 
    System.out.println(); 
} 

输出:

GOLE 
**** 
** 
0

这是一个良好的开端。

我会做下一个是改变HashMapLinkedHashMap这样我们就可以保持字符的顺序,并添加long知道次的字符出现的最大数量。通过该LinkedHashMap迭代

public void myFunction(String str) { 
int length = str.length(); 
long maxOcurrences = 0; 
LinkedHashMap<Character, Integer> hm = new LinkedHashMap<>(); 
for(int i=0;i<length;i++){ 
    char ch = str.charAt(i); 
    long nextValue; 
    if(hm.containsKey(ch)){ 
     nextValue = hm.get(ch)+1 
     hm.put(ch, nextValue);    
    } 
    else { 
     nextValue = 1; 
     hm.put(ch, nextValue); 
    } 

    if(nextValue > maxOcurrences) 
    {maxOcurrences = nextValue;} 


} 
    System.out.println(hm); 
} 

接下来,我将打印的人物依次为:因此,我将你当前的代码更改为类似。喜欢的东西:

for (Map.Entry<Character, Integer> entry : hm.entrySet()) { 
    System.out.print(entry.getKey()); 
} 
System.out.println(); 

最后,我将创建一个循环,迭代maxOcurrences次,如果需要打印*

for(int i = 0; i < maxOcurrences; i++) 
{ 
    //Iterate over each character again 
    for (Map.Entry<Character, Integer> entry : hm.entrySet()) { 
     if(entry.getValue() > i) 
     { 
      //Print Star 
      System.out.print("*"); 
     }else{ 
      //Print space 
      System.out.print(" "); 
     } 
     System.out.println(); 
    } 
} 
+0

您可以在遍历按键时捕捉第一行的大小写。这样你只需要遍历一次地图。 – gonzo

+0

@gonzo感谢您的意见!这是真的,但差别并不是那么大,如果没有'if's,额外的循环往往会花费更多的CPU。 –