This week's giveaway is in the JDBC forum.
We're giving away four copies of Java Database Connections & Transactions (e-book only) and have Marco Behler on-line!
See this thread for details.
Win a copy of Java Database Connections & Transactions (e-book only) this week in the JDBC forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Knute Snortum
  • Paul Clapham
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Frits Walraven
Bartenders:
  • Ganesh Patekar
  • Tim Holloway
  • salvin francis

String in java  RSS feed

 
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
 
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.
 
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.
 
Sheriff
Posts: 21747
102
Chrome Eclipse IDE Java Spring Ubuntu VI Editor 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
 
If you have a bad day in October, have a slice of banana cream pie. And this tiny ad:
how do I do my own kindle-like thing - without amazon
https://coderanch.com/t/711421/engineering/kindle-amazon
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!