|
| 1 | +// Highest Occuring Character |
| 2 | +// Send Feedback |
| 3 | +// For a given a string(str), find and return the highest occurring character. |
| 4 | +// Example: |
| 5 | +// Input String: "abcdeapapqarr" |
| 6 | +// Expected Output: 'a' |
| 7 | +// Since 'a' has appeared four times in the string which happens to be the highest frequency character, the answer would be 'a'. |
| 8 | +// If there are two characters in the input string with the same frequency, return the character which comes first. |
| 9 | +// Consider: |
| 10 | +// Assume all the characters in the given string to be in lowercase always. |
| 11 | +// Input Format: |
| 12 | +// The first and only line of input contains a string without any leading and trailing spaces. |
| 13 | +// Output Format: |
| 14 | +// The only line of output prints the updated string. |
| 15 | +// Note: |
| 16 | +// You are not required to print anything explicitly. It has already been taken care of. |
| 17 | +// Constraints: |
| 18 | +// 0 <= N <= 10^6 |
| 19 | +// Where N is the length of the input string. |
| 20 | + |
| 21 | +// Time Limit: 1 second |
| 22 | +// Sample Input 1: |
| 23 | +// abdefgbabfba |
| 24 | +// Sample Output 1: |
| 25 | +// b |
| 26 | +// Sample Input 2: |
| 27 | +// xy |
| 28 | +// Sample Output 2: |
| 29 | +// x |
| 30 | + |
| 31 | +import java.util.Scanner; |
| 32 | + |
| 33 | +public class HighestOccuringCharacter { |
| 34 | + public static void main(String[] args) { |
| 35 | + Scanner s = new Scanner(System.in); |
| 36 | + System.out.print("Enter The String Here Brother : "); |
| 37 | + String str = s.nextLine(); |
| 38 | + char ans = highestOccuringCharcter(str); |
| 39 | + System.out.println("Output : "+ ans); |
| 40 | + s.close(); |
| 41 | + |
| 42 | + } |
| 43 | + |
| 44 | + public static char highestOccuringCharcter(String str) |
| 45 | + { |
| 46 | + if(str.length()==0) |
| 47 | + { |
| 48 | + return ' '; |
| 49 | + } |
| 50 | + |
| 51 | + int frequency[] = new int[256]; |
| 52 | + for(int i=0;i<frequency.length;i++) |
| 53 | + { |
| 54 | + frequency[i] = 0; |
| 55 | + } |
| 56 | + |
| 57 | + for(int i=0;i<str.length();i++) |
| 58 | + { |
| 59 | + char ch = str.charAt(i); |
| 60 | + frequency[ch]++; |
| 61 | + } |
| 62 | + |
| 63 | + int max = Integer.MIN_VALUE; |
| 64 | + char output = str.charAt(0); |
| 65 | + for (int i = 0; i < str.length(); i++) { |
| 66 | + char ch = str.charAt(i); |
| 67 | + if(frequency[ch]>max) |
| 68 | + { |
| 69 | + max = frequency[ch]; |
| 70 | + output = ch; |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + return output; |
| 75 | + } |
| 76 | +} |
0 commit comments