patternjavaModerate
Checking that all occurrences of 'g' have another 'g' as a neighbor
Viewed 0 times
neighboroccurrencesallcheckingthatanotherhave
Problem
We'll say that a lowercase 'g' in a string is "happy" if there is another 'g' immediately to its left or right. Return true if all the g's in the given string are happy.
This is my code so far, which I think is very messy.
gHappy("xxggxx") → true
gHappy("xxgxx") → false
gHappy("xxggyygxx") → falseThis is my code so far, which I think is very messy.
public boolean gHappy(String str)
{
for(int i=1;i<str.length()-1;i++)
{
if(str.charAt(i)=='g')
if(str.charAt(i-1)!='g'&&str.charAt(i+1)!='g')
return false;
}
if(str.length()==1)
return false;
if(str.equals(""))
return true;
if(str.charAt(str.length()-1)=='g')
if(str.charAt(str.length()-2)!='g')
return false;
return true;
}Solution
Other answers have good input on a number of factors I agree with, especially about the early-return logic, the bugs that were pointed out, and the bracing strategies.
My suggestion though, is to use a different (the right?) tool for the job.
Regular expressions are a tool that are designed for text processing, and a well-crafted expression is typically faster and more concise than the hand-coded alternative. Regular expressions are not always the solution, but in this case, the result would be simpler to read (for someone familiar with them).
In this case, the logic requires checking that all 'g' chars are happy for the check to return true. Alternatively, to make sure there are no unhappy 'g' chars.
The expression to check for unhappy 'g' chars will be:
That expression says "Match any 'g' that has no 'g' before it, and no 'g' after it.
Then, you can use it as:
I have put together an Ideone example here.
My suggestion though, is to use a different (the right?) tool for the job.
Regular expressions are a tool that are designed for text processing, and a well-crafted expression is typically faster and more concise than the hand-coded alternative. Regular expressions are not always the solution, but in this case, the result would be simpler to read (for someone familiar with them).
In this case, the logic requires checking that all 'g' chars are happy for the check to return true. Alternatively, to make sure there are no unhappy 'g' chars.
The expression to check for unhappy 'g' chars will be:
private static final Pattern UNHAPPYG = Pattern.compile("(?<!g)g(?!g)");That expression says "Match any 'g' that has no 'g' before it, and no 'g' after it.
Then, you can use it as:
private static final boolean gHappy(String str) {
return !UNHAPPYG.matcher(str).find();
}I have put together an Ideone example here.
Code Snippets
private static final Pattern UNHAPPYG = Pattern.compile("(?<!g)g(?!g)");private static final boolean gHappy(String str) {
return !UNHAPPYG.matcher(str).find();
}Context
StackExchange Code Review Q#71276, answer score: 13
Revisions (0)
No revisions yet.