2014-02-13 64 views
1

給定段落作爲輸入,找到最頻繁出現的字符。請注意,角色的情況並不重要。如果不止一個字符具有相同的最大發生頻率,則返回所有這些字符 我正在嘗試這個問題,但我沒有結果。以下是我試過的代碼,但它有許多錯誤,我無法糾正:如何使用Java查找字符串中最常出現的字符?

public class MaximumOccuringChar { 

    static String testcase1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today."; 

    public static void main(String[] args) 
    { 
     MaximumOccuringChar test = new MaximumOccuringChar(); 
     char[] result = test.maximumOccuringChar(testcase1); 
     System.out.println(result); 
    } 

    public char[] maximumOccuringChar(String str) 
    { 
     int temp = 0; 
     int count = 0; 
     int current = 0; 

     char[] maxchar = new char[str.length()]; 

     for (int i = 0; i < str.length(); i++) 
     { 
      char ch = str.charAt(i); 

      for (int j = i + 1; j < str.length(); j++) 
      { 
       char ch1 = str.charAt(j); 

       if (ch != ch1) 
       { 
        count++; 
       } 
      } 

      if (count > temp) 
      { 
       temp = count; 
       maxchar[current] = ch; 
       current++; 
      } 
     } 
     return maxchar; 
    } 
} 
+0

的可能重複[如何返回最長序列在java中的字符串中的字符?](http://stackoverflow.com/questions/21748970/how-to-return-longest-sequence-of-chars-in-a-string-in-java) – Maroun

+0

好的,什麼是你的問題? – AlexR

+0

這是'Map '的典型情況,其中鍵是字符,因此數量有限,值是頻率。解決方案是O(N) - 一次掃描來填充地圖,一次掃描通過一張小地圖找到最高頻率。 –

回答

1

你已經得到了你的答案在這裏:https://stackoverflow.com/a/21749133/1661864

這是一個最簡單的方法我能想象。

import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 

public class MaximumOccurringChar { 

    static final String TEST_CASE_1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today. Help!"; 


    public static void main(String[] args) { 
     MaximumOccurringChar test = new MaximumOccurringChar(); 
     List<Character> result = test.maximumOccurringChars(TEST_CASE_1, true); 
     System.out.println(result); 
    } 


    public List<Character> maximumOccurringChars(String str) { 
     return maximumOccurringChars(str, false); 
    } 

    // set skipSpaces true if you want to skip spaces 
    public List<Character> maximumOccurringChars(String str, Boolean skipSpaces) { 
     Map<Character, Integer> map = new HashMap<>(); 
     List<Character> occurrences = new ArrayList<>(); 
     int maxOccurring = 0; 

     // creates map of all characters 
     for (int i = 0; i < str.length(); i++) { 
      char ch = str.charAt(i); 

      if (skipSpaces && ch == ' ')  // skips spaces if needed 
       continue; 

      if (map.containsKey(ch)) { 
       map.put(ch, map.get(ch) + 1); 
      } else { 
       map.put(ch, 1); 
      } 

      if (map.get(ch) > maxOccurring) { 
       maxOccurring = map.get(ch);   // saves max occurring 
      } 
     } 

     // finds all characters with maxOccurring and adds it to occurrences List 
     for (Map.Entry<Character, Integer> entry : map.entrySet()) { 
      if (entry.getValue() == maxOccurring) { 
       occurrences.add(entry.getKey()); 
      } 
     } 

     return occurrences; 
    } 
} 
3

你爲什麼不乾脆用了N參數信桶(N =的字母數)?沿着字符串走,並增加相應的字母桶。時間複雜度爲O(n),空間複雜度爲O(N)

+0

+1你只需要26個字母的桶。 –

+1

當然(約26)? ü,ö,Î,я...和A,a,B,b,C,c,... –

0
import java.util.Scanner; 

public class MaximumOccurringChar{ 

static String testcase1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today."; 

public static void main(String[] args) { 
    MaximumOccurringChar test = new MaximumOccurringChar(); 
    String result = test.maximumOccuringChar(testcase1); 
    System.out.println(result); 
} 

public String maximumOccuringChar(String str) { 
    int temp = 0; 
    int count = 0; 
    int current = 0; 
    int ind = 0; 
    char[] arrayChar = {'a','b' , 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; 
    int[] numChar = new int[26]; 
    char ch; 
    String s=""; 
    str = str.toLowerCase(); 
    for (int i = 0; i < 26; i++) { 
     count = 0; 
     for (int j = 0; j < str.length(); j++) { 
      ch = str.charAt(j); 
      if (arrayChar[i] == ch) { 
       count++; 
      } 
     } 
     numChar[i] = count++; 
    } 
    temp = numChar[0]; 

    for (int i = 1; i < numChar.length; i++) { 
     if (temp < numChar[i]) { 
      temp = numChar[i]; 

      ind = i; 
      break; 
     } 
    } 
     System.out.println(numChar.toString()); 
     for(int c=0;c<26;c++) 
     { 
      if(numChar[c]==temp) 
      s+=arrayChar[c]+" "; 


     } 


    return s; 

    } 
    } 
+0

此代碼有錯誤:(我測試它只是使用單詞'你好',它返回'heo' – 2017-08-07 03:40:17

0

算法: -

  1. 複製由字符字符串字符的LinkedHashMap。

    • 如果它的一個新的角色,然後插入新的字符,1
    • 如果字符是在LinkedHashMap中已經存在,那麼通過遞增1。
  2. 遍歷一個條目的更新值通過一個並將其存儲在一個Entry對象中。

    • 如果存儲在條目對象鍵的值大於或等於當前條目,然後什麼也不做
    • 否則,存儲條目對象
  3. 新條目循環通過,只需打印後Entry對象的鍵和值。

公共類Characterop {

public void maxOccur(String ip) 
{ 

    LinkedHashMap<Character, Integer> hash = new LinkedHashMap(); 
    for(int i = 0; i<ip.length();i++) 
    { 
     char ch = ip.charAt(i); 
     if(hash.containsKey(ch)) 
     { 
      hash.put(ch, (hash.get(ch)+1)); 

     } 
     else 
     { 
      hash.put(ch, 1); 
     } 
    } 

    //Set set = hash.entrySet(); 
    Entry<Character, Integer> maxEntry = null; 
    for(Entry<Character,Integer> entry : hash.entrySet()) 
    { 
     if(maxEntry == null) 
     { 
      maxEntry = entry; 
     } 

     else if(maxEntry.getValue() < entry.getValue()) 
     { 
      maxEntry = entry; 
     } 
    } 
    System.out.println(maxEntry.getKey()); 


} 
public static void main(String[] args) { 
    Characterop op = new Characterop(); 
    op.maxOccur("AABBBCCCCDDDDDDDDDD"); 
} 

}

0

大O下面的解決方案是隻O(N)。請分享你的意見。

public class MaxOccuringCahrsInStr { 

     /** 
     * @param args 
     */ 
     public static void main(String[] args) { 
      // TODO Auto-generated method stub 
      String str = "This is Sarthak Gupta"; 

      printMaxOccuringChars(str); 

     } 

     static void printMaxOccuringChars(String str) { 
      char[] arr = str.toCharArray(); 
      /* Assuming all characters are ascii */ 
      int[] arr1 = new int[256]; 
      int maxoccuring = 0; 

      for (int i = 0; i < arr.length; i++) { 
       if (arr[i] != ' ') { // ignoring space 
        int val = (int) arr[i]; 
        arr1[val]++; 
        if (arr1[val] > maxoccuring) { 
         maxoccuring = arr1[val]; 
        } 
       } 

      } 

      for (int k = 0; k < arr1.length; k++) { 
       if (maxoccuring == arr1[k]) { 
        char c = (char) k; 
        System.out.print(c + " "); 

       } 

      } 

     } 

    } 
0
function countString(ss) 
     { 
      var maxChar=''; 
      var maxCount=0; 
      for(var i=0;i<ss.length;i++) 
      { 
       var charCount=0; 
       var localChar='' 
       for(var j=i+1;j<ss.length;j++) 
       { 
        if(ss[i]!=' ' && ss[i] !=maxChar) 
        if(ss[i]==ss[j]) 
        { 
         localChar=ss[i]; 
         ++charCount; 
        } 
       } 
       if(charCount>maxCount) 
       { 
        maxCount=charCount; 
        maxChar=localChar; 
       } 
      } 
      alert(maxCount+""+maxChar) 
     } 
0

另一種方式來解決這個問題。更簡單的一個。

public static void main(String[] args) { 

    String str= "aaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbcddddeeeeee"; 
    String str1 = "dbc"; 

    if(highestOccuredChar(str) != ' ') 
    System.out.println("Most Frequently occured Character ==> " +Character.toString(highestOccuredChar(str))); 
    else 
     System.out.println("The String doesn't have any character whose occurance is more than 1"); 
} 

private static char highestOccuredChar(String str) { 

    int [] count = new int [256]; 

    for (int i=0 ;i<str.length() ; i++){ 
     count[str.charAt(i)]++; 
    } 

    int max = -1 ; 
    char result = ' ' ; 

    for(int j =0 ;j<str.length() ; j++){ 
     if(max < count[str.charAt(j)] && count[str.charAt(j)] > 1) { 
      max = count[str.charAt(j)]; 
      result = str.charAt(j); 
     } 
    } 

    return result; 

} 
0
public void countOccurrence(String str){ 
    int length = str.length(); 
    char[] arr = str.toCharArray(); 
    HashMap<Character, Integer> map = new HashMap<>(); 
    int max = 0; 

    for (char ch : arr) { 
     if(ch == ' '){ 
      continue; 
     } 
     if (map.containsKey(ch)) { 
      map.put(ch, map.get(ch) + 1); 
     } else { 
      map.put(ch, 1); 
     } 
    } 

    Set<Character> set = map.keySet(); 

    for (char c : set) { 
     if (max == 0 || map.get(c) > max) { 
      max = map.get(c); 
     } 
    } 

    for (Character o : map.keySet()) { 
     if (map.get(o).equals(max)) { 
      System.out.println(o); 
     } 
    } 
    System.out.println(""); 
} 

public static void main(String[] args) { 
    HighestOccurence ho = new HighestOccurence(); 

    ho.countOccurrence("aabbbcde"); 
} 
0
public void stringMostFrequentCharacter() { 
    String str = "My string lekdcd dljklskjffslk akdjfjdkjs skdjlaldkjfl;ak adkj;kfjflakj alkj;ljsfo^wiorufoi$*#&$ *******"; 
    char[] chars = str.toCharArray(); //optionally - str.toLowerCase().toCharArray(); 
    int unicodeMaxValue = 65535; // 4 bytes 
    int[] charCodes = new int[unicodeMaxValue]; 
    for (char c: chars) { 
     charCodes[(int)c]++; 
    } 
    int maxValue = 0; 
    int maxIndex = 0; 
    for (int i = 0; i < unicodeMaxValue; i++) { 
     if (charCodes[i] > maxValue) { 
      maxValue = charCodes[i]; 
      maxIndex = i; 
     } 
    } 
    char maxChar = (char)maxIndex; 
    System.out.println("The most frequent character is >" + maxChar + "< - # of times: " + maxValue); 
} 
0

對於簡單的字符串操作,可以做這個程序爲:

package abc; 
import java.io.*; 

public class highocc 
{ 
     public static void main(String args[])throws IOException 
     { 
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
      System.out.println("Enter any word : "); 
      String str=in.readLine(); 
      str=str.toLowerCase(); 
      int g=0,count,max=0;; 
      int ar[]=new int[26]; 
      char ch[]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; 
       for(int i=0;i<ch.length;i++) 
       { 
        count=0; 
        for(int j=0;j<str.length();j++) 
        { 
         char ch1=str.charAt(j); 
         if(ch[i]==ch1) 
          count++; 
        } 
        ar[i]=(int) count; 
       } 
       max=ar[0]; 
       for(int j=1;j<26;j++) 
       { 
        if(max<ar[j]) 
         { 
          max=ar[j]; 
          g=j; 
         } 
       } 
       System.out.println("Maximum Occurence is "+max+" of character "+ch[g]); 
      } 
} 

樣品輸入1:PRATIK是一個好的程序員

採樣輸出1:最大發生難度3字符a

樣品輸入2:HELLO WORLD

樣品輸出2:最大發生難度性格升3

0
maxOccu m = new maxOccu(); 
String str = "moinnnnaaooooo"; 
char[] chars = str.toCharArray(); 
Arrays.sort(chars); 
str = new String(chars); 
System.out.println(str); 
m.maxOccurence(str); 

void maxOccurence(String str) { 
    char max_char = str.charAt(0), 
    cur_char, 
    prev = str.charAt(0); 
    int cur_count = 0, 
    max_count = 0, 
    n; 
    n = str.length(); 
    for (int i = 0; i < n; i++) { 
     cur_char = str.charAt(i); 
     if (cur_char != prev) cur_count = 0; 
     if (str.charAt(i) == cur_char) { 
      cur_count++; 
     } 
     if (cur_count > max_count) { 
      max_count = cur_count; 
      max_char = cur_char; 
     } 
     prev = cur_char; 
    } 
    System.out.println(max_count + "" + max_char); 
} 
+0

算法; 1.首先對字符串進行排序2.然後將cur_char與prevoius字符進行比較,如果兩者匹配,則增加cur_count並且是cur_count> max_count,然後cur_char是Max_char 3.if cur_char!= prev我們從0開始cur_count – MOIN

0
public class HigestOccurredCharTest { 

    public static void main(String[] args) { 
     System.out.println("Enter the char string to check higest occurrence"); 
     Scanner scan = new Scanner(System.in); 
     String str = scan.next(); 
     if(str != null && !str.isEmpty()){ 
      Map<Character, Integer> map = countOccurrence(str); 
      getHigestOccurrenceChar(map); 
     }else{ 
      System.out.println("enter valid string"); 
     } 
    } 

    public static Map<Character, Integer> countOccurrence(String str){ 
     char strArr[] = str.toCharArray(); 
     Map<Character, Integer> map = new HashMap<Character , Integer>(); 
     for (Character ch : strArr) { 
      if(map.containsKey(ch)){ 
       map.put(ch, map.get(ch)+1); 
      }else{ 
       map.put(ch, 1); 
      } 
     } 
     return map; 
    } 

    public static void getHigestOccurrenceChar(Map<Character, Integer> map){ 
     Character ch = null; 
     Integer no = 0; 
     Set<Entry<Character, Integer>> entrySet = map.entrySet(); 
     for (Entry<Character, Integer> entry : entrySet) { 
      if(no != 0 && ch != null){ 
       if(entry.getValue() > no){ 
        no = entry.getValue(); 
        ch = entry.getKey(); 
       } 
      }else{ 
       no = entry.getValue(); 
        ch = entry.getKey(); 
      } 


     } 
     System.out.println(ch+ " Higest occurrence char is "+ no); 
    } 

} 
0

嘗試像那: -

 string inputString = "COMMECEMENT"; 
     List<Tuple<char, int>> allCharListWithLength = new List<Tuple<char, int>>(); 
     List<char> distinchtCharList = inputString.Select(r => r).Distinct().ToList(); 
     for (int i = 0; i < distinchtCharList.Count; i++) 
     { 
      allCharListWithLength.Add(new Tuple<char, int>(distinchtCharList[i], inputString.Where(r => r == 
      distinchtCharList[i]).Count())); 
     } 
     Tuple<char, int> charWithMaxLength = allCharListWithLength.Where(r => r.Item2 == allCharListWithLength.Max(x => x.Item2)).FirstOrDefault(); 
相關問題