java - How can I make this String counter code more efficient? -


here code. method counter counts number of times each alphabet occurs in string.

public class hard{

public static void counter (string s) {    (int n = 0; n < s.length() ; n++) {         int count = 0 ,bool = 1;         if (n > 0) {              (int l = n-1 ; l >= 0  ; l--) {              if (s.charat(n) == s.charat(l)) {bool = 0; }                    }         }         (int f = 0; f < s.length() ; f++ ) {          if (bool == 0) { break ; }           if (s.charat(n) == s.charat(f)) {count++;}        }         if (count > 0 ) {           system.out.println(s.charat(n)+" appears "+count+" times.");        }   }     

}

 public static void main (string[] args) {    counter("bbaddadxzxwfgb$.fgfdf");                    } 

}

assuming you're using java , assuming , counted same letter.

public static int[] counter (string s) {     int [] countarr = new int[26];     for(int i=0; i<s.length(); i++) {         char charati = s.charat(i);         if(character.isletter(charati)) {             countarr[character.isuppercase(charati) ? charati - 'a' : charati - 'a']++;         }     }     return countarr; }  public static void main (string[] args) {     int [] countarr = counter("asif , abid.");     for(int = 0; i<countarr.length; i++) {         if(countarr[i] > 0) {             system.out.println(messageformat.format("{0} appears {1} times", (char)(i + 'a'), countarr[i]));         }     } } 

the key optimization lies in fact performs one pass no nested loops , once have information require, worry how present user.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -