查找字符串中出现的最大和最小字符的Java程序

1 说明

在此程序中,我们需要计算字符串中存在的每个字符,并找出出现的最大和最小字符。

Grass is greener on the other side

在上面的示例中,字符“ a”在字符串中仅出现一次。因此,它是出现的最少字符,并用红色突出显示。字符e在整个字符串中出现的次数最多,即6次。因此,它是出现的最大字符,并用绿色突出显示。

2 算法思路

  • 步骤1:开始
  • 步骤2: 定义 String str =“grass is greener on the other side”
  • 步骤3:初始化minChar,maxChar。
  • 步骤4:定义i,j,min,max
  • 步骤5:将str转换为char string []。
  • 步骤6: SET i = 0。直到i重复步骤7至步骤11
  • 步骤7: SET数组freq [i] = 1
  • 步骤8:设定j = i + 1。直到j将步骤9重复到步骤10
  • 步骤9:如果(string [i] == string [j] && string [i]!=''&& string [i]!='0'),
                  则
                  freq [i] = freq [i] + 1
                  SET string [ j] = 0
  • 步骤10: j = j +1
  • 步骤11: i = i + 1
  • 步骤12:SET min = max = freq[0]
  • 步骤13: SET i = 0。直到i重复步骤14至步骤16
  • 步骤14:IF(min>freq[i] && freq[i]!=0) then
                  min = freq[i]
                  minChar[] = string[i]
  • 步骤15:IF max is lesser than freq[i]then
                  max = freq[i]
                  maxChar[] = string[i]
  • 步骤16: i = i +1
  • 步骤17:打印minChar
  • 步骤18:打印maxChar
  • 步骤19:结束

3 程序实现

/**
 * 一点教程网: http://www.yiidian.com
 */
public class Characters     
   
   public static void main(String[] args) {    
      String str = "grass is greener on the other side";    
      int[] freq = new int[str.length()];    
      char minChar = str.charAt(0), maxChar = str.charAt(0);    
      int i, j, min, max;            
          
      //Converts given string into character array    
      char string[] = str.toCharArray();    
          
      //Count each word in given string and store in array freq    
      for(i = 0; i < string.length; i++) {    
          freq[i] = 1;    
          for(j = i+1; j < string.length; j++) {    
              if(string[i] == string[j] && string[i] != ' ' && string[i] != '0') {    
                  freq[i]++;    
                      
                  //Set string[j] to 0 to avoid printing visited character    
                  string[j] = '0';    
              }    
          }    
      }    
          
      //Determine minimum and maximum occurring characters    
      min = max = freq[0];    
      for(i = 0; i <freq.length; i++) {    
              
          //If min is greater than frequency of a character     
          //then, store frequency in min and corresponding character in minChar    
          if(min > freq[i] && freq[i] != '0') {    
              min = freq[i];    
              minChar = string[i];    
          }    
          //If max is less than frequency of a character     
          //then, store frequency in max and corresponding character in maxChar    
          if(max < freq[i]) {    
              max = freq[i];    
              maxChar = string[i];    
          }    
      }    
          
      System.out.println("Minimum occurring character: " + minChar);    
      System.out.println("Maximum occurring character: " + maxChar);    
  }    
   

以上代码输出结果为:

Minimum occurring character: a
Maximum occurring character: e

 

热门文章

优秀文章