Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String in java

 
Tarik Ansari
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
i had a question which was asked in an interview to analyse my problem solving ability.

Snippet:
String a ="abcba";

Based on the occurance of the alphabets it should append the appropriate numbers before the alphabets.

So String a ="abcba" should be replaced by "2a2bc".

Please suggest a snippet which will return the result for me.

Thanks in advance
 
Lester Burnham
Rancher
Posts: 1337
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Assuming we're talking about lowercase ASCII characters only, the solution could involve a "int[] letterCount = new int[26]" field.

For a more generalized problem, a "Map<Character,Integer> letterCount = new HashMap<Character,Integer>" would work.

In either case two loops would be necessary - one to count the letters, and one to create the resulting string.
 
Siddhesh Deodhar
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should be taking each character and put it to a map and raise "value" every time you find occurrence of key example
iterative representation of String s will be

<a,1>
<b,1>
<c,1>

<a,2>
<b,2>
<c,1>


and than print this in desired way.
 
Rob Spoor
Sheriff
Pie
Posts: 20667
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lester Burnham wrote:For a more generalized problem, a "Map<Character,Integer> letterCount = new HashMap<Character,Integer>" would work.

Or:
- a LinkedHashMap if insertion order should be used
- a TreeMap if alphabetical order should be used
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic