How can I count the number of occurrences of a simple pattern in a string?
-
For this question, a "pair" in a string is defined as a situation where two instances of one character are separated by another character. So in "AxA" the A's make a pair. Pairs can overlap, so "AxAxA" contains three pairs; two for A and one for x. Further examples: countPairs("axa") → 1 countPairs("axax") → 2 countPairs("axbx") → 1 I was asked how to compute the number of pairs in a given string in an interview yesterday, and I'm not sure how to do it.
-
Answer:
An O(n) solution would be to iterate the string (from 0 to length-2) and (using charAt(..)) to verify whether the current character is equal to the current+2. If so, increment a pairsCount variable int pairsCount = 0; for (int i = 0; i < str.length() - 2; i ++) { if (str.charAt(i) == str.charAt(i + 2)) { pairsCount ++; } }
Deepak at Stack Overflow Visit the source
Other answers
The previous awser don't covert the fact that the caracter in the middle (the separator) must be different. For this question, a "pair" in a string is defined as a situation where two instances of one character are separated by another character. So in "AxA" the A's make a pair. Pairs can overlap, so "AxAxA" contains three pairs; two for A and one for x. Must this characters be different ? Here what I though if it's have to be different... int trueNbPair =0; for (int i=1;i<str.length()-1;i++) { char prev = str.charAt(i-1); char current = str.charAt(i); char next = str.charAt(i+1); if (prev == next && current!= prev) { trueNbPair++; } }
Chris
Related Q & A:
- How can i access the number of questions asked on stackoverflow?Best solution by Meta Stack Overflow
- How can I make JAXB-generated classes participate in a visitor pattern?Best solution by Stack Overflow
- Where can I find good a tutorial for creating a simple flash movie using Adobe Flash CS4?Best solution by Graphic Design
- How can I block a number on my cell phone?Best solution by eHow old
- How can i track a number?Best solution by eHow old
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.