Check Consecutive 13 digits in java - java

Hi All I'm using the following function to check the Consecutive digits in java
The issue im facing here is it works for the first Consecutive digits only
For example it work for 123456789123456XXXX
but want this to work Consecutive any where
XXXX123456789123456 or XX123456789123456XX
Update
Now if i found 13 Consecutive digits then i need to pass all Consecutive digits to the mask function
and my result should be
something like this
for input 123456789123456XXXX result should be 123456%%%%%3456XXXX
for input XXXX123456789123456 result should be XX123456%%%%%3456XX
Please help me to solve this
My Code
public void checkPosCardNoAndMask(String cardNo) {
String maskNumber = "";
String starValue = "";
boolean isConsecutive = false;
int checkConsecutive = 0;
for (int i = 0, len = cardNo.length(); i < len; i++) {
if (Character.isDigit(cardNo.charAt(i))) {
maskNumber = maskNumber + cardNo.charAt(i);
} else {
if (checkConsecutive >= 13)
isConsecutive = true;
else
break;
starValue = starValue + cardNo.charAt(i);
}
checkConsecutive++;
}
if (isConsecutive)
{
cardNo = maskCCNumber(maskNumber) + starValue;
System.out.printIn("Consecutive found!!:"+cardNo);
}
else
{
System.out.printIn("Consecutive not found!!:"+cardNo);
}
}
Masking logic
public String maskCCNumber(String ccNo)
{
String maskCCNo = "";
for (int i = 0; i < ccNo.length(); i++)
{
if (i > 5 && i < ccNo.length() - 4)
{
maskCCNo = maskCCNo + '%';
}
else
{
maskCCNo = maskCCNo + ccNo.charAt(i);
}
}
return maskCCNo;
}

With regex you can do this way:
String str = "XX123456789123456XX";
if (str.matches(".*\\d{13}.*")) {
System.out.println(true);
Pattern compile = Pattern.compile("\\d+");
Matcher matcher = compile.matcher(str);
matcher.find();
String masked = maskCCNumber(matcher.group());//send 123456789123456 and returns 123456%%%%%3456
String finalString=str.replaceAll("\\d+", masked);// replace all digits with 123456%%%%%3456
System.out.println(finalString);
}
Output:
true
XX123456%%%%%3456XX

There are few issues:
You're breaking out of else, when first time you find non-digit character. This will skip any consecutive digit coming after that. So, you should not break.
In fact, you should add break out of the loop once you find 13 consecutive digit.
You're not really looking for consecutive digits, but just total number of non-cosnecutive digits. At least the current logic without break would work this way. You should reset the checkConsecutive variable to 0 when you find a non-digit character.
So, changing your for loop to this will work:
for (int i = 0, len = cardNo.length(); i < len; i++)
{
if (Character.isDigit(cardNo.charAt(i))) {
checkConsecutive++;
} else if (checkConsecutive == 13) {
isConsecutive = true;
break;
} else {
checkConsecutive = 0;
}
}
Of course I don't know what is starValue and maskValue, so I've removed it. You can add it appropriately.
BTW, this problem can also be solved with regex:
if (cardNo.matches(".*\\d{13}.*")) {
System.out.println("13 consecutive digits found");
}

try this
public void checkPosCardNoAndMask(String cardNo) {
if (cardNo.matches("[0-9]{13,}")) {
System.out.println("Consecutive found!!");
} else {
System.out.println("Consecutive not found!!");
}
}

If you want to work with your code then make one change
public void checkPosCardNoAndMask(String cardNo) {
String maskNumber = "";
String starValue = "";
boolean isConsecutive = false;
int checkConsecutive = 0;
for (int i = 0, len = cardNo.length(); i < len; i++) {
if (Character.isDigit(cardNo.charAt(i))) {
maskNumber = maskNumber + cardNo.charAt(i);
checkConsecutive++;
} else {
if (checkConsecutive >= 13)
{isConsecutive = true;break;}
else
checkConsecutive=0;
starValue = starValue + cardNo.charAt(i);
}
}
if (isConsecutive) {
System.out.printIn("Consecutive found!!");
} else {
System.out.printIn("Consecutive not found!!");
}
}

try this
public static void checkPosCardNoAndMask(String cardNo) {
int n = 1;
char c1 = cardNo.charAt(0);
for (int i = 1, len = cardNo.length(); i < len && n < 13; i++) {
char c2 = cardNo.charAt(i);
if (c2 >= '1' && c2 <= '9' && (c2 - c1 == 1 || c2 == '1' && c1 == '9')) {
n++;
} else {
n = 0;
}
c1 = c2;
}
if (n == 13) {
System.out.println("Consecutive found!!");
} else {
System.out.println("Consecutive not found!!");
}
}

My understanding is that you want to mask card numbers in a string. There is one external dependency in following code http://commons.apache.org/proper/commons-lang/ for StringUtils
/**
* Returns safe string for cardNumber, will replace any set of 13-16 digit
* numbers in the string with safe card number.
*/
public static String getSafeString(String str) {
Pattern CARDNUMBER_PATTERN = Pattern.compile("\\d{13,16}+");
Matcher matcher = CARDNUMBER_PATTERN.matcher(str);
while (matcher.find()) {
String cardNumber = matcher.group();
if (isValidLuhn(cardNumber)) {
str = StringUtils.replace(str, cardNumber, getSafeCardNumber(cardNumber));
}
}
return str;
}
public static boolean isValidLuhn(String cardNumber) {
if (cardNumber == null || !cardNumber.matches("\\d+")) {
return false;
}
int sum = 0;
boolean alternate = false;
for (int i = cardNumber.length() - 1; i >= 0; i--) {
int n = Integer.parseInt(cardNumber.substring(i, i + 1));
if (alternate) {
n *= 2;
if (n > 9) {
n = (n % 10) + 1;
}
}
sum += n;
alternate = !alternate;
}
return (sum % 10 == 0);
}
/**
* Returns safe string for cardNumber, will keep first six and last four
* digits.
*/
public static String getSafeCardNumber(String cardNumber) {
StringBuilder sb = new StringBuilder();
int cardlen = cardNumber.length();
if (cardNumber != null) {
sb.append(cardNumber.substring(0, 6)).append(StringUtils.repeat("%", cardlen - 10)).append(cardNumber.substring(cardlen - 4));
}
return sb.toString();
}

Related

How do I reverse the order of only the digits in a string?

Given a string in Java, how can I obtain a new string where all adjacent sequences of digits are reversed?
My code:
import static java.lang.System.*;
public class P2
{
public static void main(String[] args)
{
if(args.length < 1)
{
err.printf("Usage: java -ea P2 String [...]\n");
exit(1);
}
String[] norm = new String[args.length];
for(int i = 0; i<norm.length;i++)
{
norm[i] = args[i];
}
}
public String invertDigits(String[] norm)
{
}
}
And as an example, this is what it should do:
Inputs: 1234 abc9876cba a123 312asd a12b34c56d
1234 -> 4321
abc9876cba -> abc6789cba
a123 -> a321
312asd -> 213asd
a12b34c56d -> a21b43c65d
Although the question is heavily downvoted, the proposed problem seems clear now. I chose to solve it using a regular expression match in a recursive function.
private static String reverseDigits(String s) {
// the pattern will match a sequence of 1 or more digits
Matcher matcher = Pattern.compile("\\d+").matcher(s);
// fetch the position of the next sequence of digits
if (!matcher.find()) {
return s; // no more digits
}
// keep everything before the number
String pre = s.substring(0, matcher.start());
// take the number and reverse it
String number = matcher.group();
number = new StringBuilder(number).reverse().toString();
// continue with the rest of the string, then concat!
return pre + number + reverseDigits(s.substring(matcher.end()));
}
And here's the iterative approach.
private static String reverseDigits(String s) {
//if (s.isEmpty()) return s;
String res = "";
int base = 0;
Matcher matcher = Pattern.compile("\\d+").matcher(s);
while (!matcher.hitEnd()) {
if (!matcher.find()) {
return res + s.substring(base);
}
String pre = s.substring(base, matcher.start());
base = matcher.end();
String number = matcher.group();
number = new StringBuilder(number).reverse().toString();
res += pre + number;
}
return res;
}
String str = "1234";
//indexes
int i = 0, j = str.length()-1;
// find digits (if any)
while (!Character.isDigit(str.charAt(i)) && i < str.length()) {
i++;
}
while (!Character.isDigit(str.charAt(j)) && j >= 0) {
j--;
}
// while we havent searched all the digits
while (i < j) {
// switch digits
str = str.substring(0, i) + str.charAt(j) + str.substring(i + 1, j) + str.charAt(i) + str.substring(j + 1);
i++;
j--;
// find the next digits
while (!Character.isDigit(str.charAt(i)) && i < str.length()) {
i++;
}
while (!Character.isDigit(str.charAt(j)) && j >= 0) {
j--;
}
}
System.out.println(str);
Another dynamic approach without using regex classes:
public static String reverseOnlyNumbers(String s) {
StringBuilder digits = new StringBuilder();
StringBuilder result = new StringBuilder();
boolean start = false;
for (int i = 0; i < s.length(); i++) {
Character c = s.charAt(i);
if (Character.isDigit(c)) {
start = true;
digits.append(c);
}else {
start = false;
if (digits.length() > 0) {
result.append(digits.reverse().toString());
digits = new StringBuilder();
}
result.append(c);
}
}
return start ? result.append(digits.reverse()).toString() : result.toString();
}

How could I solve this error, with my string to equation convertin calculator?

I'm writing a calculator code that solves the input whats given in string. All is good, except when it gets a negative result in the parentheses it fails badly because two operations get next to each other:
1+2*(10-11) >> 1+2*(-1) >> 1+2*-1
So where *- is, it gets "" (nothing) in the BigDecimal's constructor.
I know what's the problem, but how can I solve it?
import java.math.BigDecimal;
import java.util.ArrayList;
public class DoMath {
public static void main(String[] args) {
// Test equation goes here.
String number = "95.3+43.23*(10-11.1)";
System.out.println(doMath(number));
}
public static BigDecimal doMath(String input) {
StringBuilder builtInput = new StringBuilder(input);
StringBuilder help = new StringBuilder();
// Check if there are parenthesis in the equation.
boolean noParenthesis = true;
for (int i = 0; i < builtInput.length(); i++) {
if (builtInput.charAt(i) == 40) {
noParenthesis = false;
break;
}
}
if (noParenthesis) { // If there are no parenthesis, calculate the equation!
return calculateAndConvert(builtInput);
} else { // If there are parenthesis, breakdown to simple equations!
int parenthesePair = 0;
// Start extracting characters from the builtInput variable.
for (int i = 0; i < builtInput.length(); i++) {
// Start where we find a parentheses opener.
if (builtInput.charAt(i) == 40) {
parenthesePair = 1;
builtInput.deleteCharAt(i);
for (int j = i; j < builtInput.length(); j++) {
// If we find another opener, add one to parenthesePair variable.
if (builtInput.charAt(j) == 40) {
parenthesePair++;
}
// If we find a closer, subtract one from the given variable.
if (builtInput.charAt(j) == 41) {
parenthesePair--;
}
// If we have found the matching pair, delete it and break the for loop.
if (parenthesePair == 0) {
builtInput.deleteCharAt(j);
builtInput.insert(j, doMath(help.toString()));
break;
}
help.append(builtInput.charAt(j));
builtInput.deleteCharAt(j);
j--;
}
break;
}
}
}
System.out.println(builtInput);
return doMath(builtInput.toString());
}
public static BigDecimal calculateAndConvert(StringBuilder input) {
ArrayList<BigDecimal> listOfNumbers = new ArrayList<BigDecimal>();
StringBuilder numBay = new StringBuilder();
StringBuilder operations = new StringBuilder();
// If the first character is -, the first number is negative.
boolean firstIsNegative = false;
if (input.charAt(0) == 45) {
firstIsNegative = true;
input.deleteCharAt(0);
}
// Converting to numbers.
while (input.length() != 0) {
// If the character is a number or a dot, put it in the numBay variable and delete the char.
if (input.charAt(0) >= 48 && input.charAt(0) <= 57 || input.charAt(0) == 46) {
numBay.append(input.charAt(0));
// If the character is not a number, put it in the operations variable
// and save the number in the list (not operator characters are filtered)
} else {
listOfNumbers.add(new BigDecimal(numBay.toString()));
numBay.setLength(0);
operations.append(input.charAt(0));
}
// Delete the character.
input.deleteCharAt(0);
}
listOfNumbers.add(new BigDecimal(numBay.toString()));
// Setting first number to negative if it's needed.
if (firstIsNegative) {
listOfNumbers.set(0, listOfNumbers.get(0).negate());
}
// Calculate the result from the list and operations and return it.
return calculate(listOfNumbers, operations);
}
public static BigDecimal calculate(ArrayList<BigDecimal> list, StringBuilder ops) {
BigDecimal momentaryResult;
// Check for a multiply operation - if there is one, solve it.
for (int i = 0; i < ops.length(); i++) {
if (ops.charAt(i) == 42) {
momentaryResult = list.get(i).multiply(list.get(i + 1));
list.remove(i);
list.set(i, momentaryResult);
ops.deleteCharAt(i);
i--;
}
}
// Check for a divide operation - if there is one, solve it.
for (int i = 0; i < ops.length(); i++) {
if (ops.charAt(i) == 47) {
momentaryResult = list.get(i).divide(list.get(i + 1));
list.remove(i);
list.set(i, momentaryResult);
ops.deleteCharAt(i);
i--;
}
}
// Check for a subtract operation - if there is one, solve it.
for (int i = 0; i < ops.length(); i++) {
if (ops.charAt(i) == 45) {
momentaryResult = list.get(i).subtract(list.get(i + 1));
list.remove(i);
list.set(i, momentaryResult);
ops.deleteCharAt(i);
i--;
}
}
// Check for a plus operation - if there is one, solve it.
for (int i = 0; i < ops.length(); i++) {
if (ops.charAt(i) == 43) {
momentaryResult = list.get(i).add(list.get(i + 1));
list.remove(i);
list.set(i, momentaryResult);
ops.deleteCharAt(i);
i--;
}
}
// Return with the one remaining number that represents the result.
return list.get(0);
}
}
Edit: or would it be easier to write a new code with a different algorithm...?
I would post this as a comment to your question, but I do not have the required reputation to do so.
Anyway, since you have already recognized that the bug is the "operator" *- couldn't you make a method that would fix this problem by replacing the plus operator immediately before by a minus? Like this:
1+2*-1 >>> 1-2*1
If you want I can write you the code. But maybe it will be easier for you to adapt a solution like this in your code that is already working.
Edit - 1:
Obviously, the code should also treat the following cases:
1-2*-1 >>> 1+2*1
2*-1 >>> -2*1
Edit - 2:
Here is the code I managed to make. Let me know if you find any errors.
public int countChar(String str, char chr) {
int count = 0;
for (int k = 0; k < str.length(); k++) {
if (str.charAt(k) == chr)
count++;
}
return count;
}
public String fixBug(String eq) {
boolean hasBug = eq.contains("*-");
if (hasBug) {
String subeq;
int indbug, indp, indm;
eq = eq.replace("*-", "#");
int N = countChar(eq, '#');
for (int k = N; k > 0; k--) {
indbug = eq.indexOf('#');
subeq = eq.substring(0, indbug);
indp = subeq.lastIndexOf('+');
indm = subeq.lastIndexOf('-');
if (indp == -1 && indm == -1) {
eq = "-" + eq;
} else if (indp > indm) {
eq = eq.substring(0, indp) + '-' + eq.substring(indp + 1);
} else {
eq = eq.substring(0, indm) + '+' + eq.substring(indm + 1);
}
}
eq = eq.replace("#", "*");
}
return eq;
}

Trouble with Pattern finding Strings in a loop

My getCount() method should be returning 2 in this case but it is returning 7. I think the reason why it's counting incorrectly is because it's looping through the for 7 times because that's the length of the string. However, I simply just want to scan the string for the pattern and increment patternCount by 1 each time the pattern occurs in the string I'm scanning. Here's my code:
package a2;
public class DNAStrandAdept {
private String strand;
private String pattern;
private String passedStrand;
private int ACount;
private int CCount;
private int GCount;
private int TCount;
private int patternCount = 0;
public static void main(String[] args) {
DNAStrandAdept test = new DNAStrandAdept("AGGTTGG");
System.out.println("A count: " + test.getACount());
System.out.println("C count: " + test.getCCount());
System.out.println("G count: " + test.getGCount());
System.out.println("T count: " + test.getTCount());
System.out.println("Strand: " + test.getStrandString());
System.out.println("Strand length: " + test.getLength());
System.out.println("Pattern Count: " + test.getCount("GG"));
}
public DNAStrandAdept(String strand) {
passedStrand = strand;
if (passedStrand.contains("a") || passedStrand.contains("c")
|| passedStrand.contains("g") || passedStrand.contains("t")) {
throw new RuntimeException("Illegal DNA strand");
} else if (passedStrand.contains("1") || passedStrand.contains("2")
|| passedStrand.contains("3") || passedStrand.contains("4")
|| passedStrand.contains("5") || passedStrand.contains("6")
|| passedStrand.contains("7") || passedStrand.contains("8")
|| passedStrand.contains("9") || passedStrand.contains("0")) {
throw new RuntimeException("Illegal DNA Strand");
} else if (passedStrand.contains(",") || passedStrand.contains(".")
|| passedStrand.contains("?") || passedStrand.contains("/")
|| passedStrand.contains("<") || passedStrand.contains(">")) {
throw new RuntimeException("Illegal DNA Strand");
}
}
public int getACount() {
for (int i = 0; i < passedStrand.length(); i++) {
if (passedStrand.charAt(i) == 'A') {
ACount++;
}
}
return ACount;
}
public int getCCount() {
for (int i = 0; i < passedStrand.length(); i++) {
if (passedStrand.charAt(i) == 'C') {
CCount++;
}
}
return CCount;
}
public int getGCount() {
for (int i = 0; i < passedStrand.length(); i++) {
if (passedStrand.charAt(i) == 'G') {
GCount++;
}
}
return GCount;
}
public int getTCount() {
for (int i = 0; i < passedStrand.length(); i++) {
if (passedStrand.charAt(i) == 'T') {
TCount++;
}
}
return TCount;
}
public String getStrandString() {
return passedStrand;
}
public int getLength() {
return passedStrand.length();
}
public int getCount(String pattern) {
for (int i = 0; i < passedStrand.length(); i++) {
if (passedStrand.contains(pattern)) {
patternCount++;
}
}
return patternCount;
}
public int findPattern(String pattern, int startIndex) {
return 0;
}
}
Here is my output:
A count: 1
C count: 0
G count: 4
T count: 2
Strand: AGGTTGG
Strand length: 7
Pattern Count: 7
Notice your for loop:
for (int i = 0; i < passedStrand.length(); i++) {
if (passedStrand.contains(pattern)) {
patternCount++;
}
}
If the pattern is there in passedStrand, it will always be true. It doesn't really depend upon any part of the loop. Since the loop is running passedStrand.length() number of times, that condition will be checked that many times. And every time, since it is true, the patternCount is incremented. And hence the final value of patternCount will be passedStrand.length();.
What you rather want to do is, starting at every index, check if next pattern.length() number of characters, make up a string equal to pattern. If yes, then increment patternCount. So, you would need to make use of substring method here:
int patternLen = pattern.length();
for (int i = 0; i < passedStrand.length() - patternLen + 1; i++) {
if (passedStrand.substring(i, i + patternLen).equals(pattern)) {
patternCount++;
}
}
Also notice that, the loop will not really run till the end of passedStrand string. You just need to run till the index, from where there is a possibility of complete occurrence of pattern string.
This method creates extra String objects inside the for loop, due to substring invocation. You can avoid this by using String#indexOf method. You just keep on finding the next index of the pattern in the passedStrand, till you get the index as -1, where it ends.
int startIndex = passedStrand.indexOf(pattern);
while (startIndex != -1) {
patternCount++;
startIndex = passedStrand.indexOf(pattern, startIndex + pattern.length());
}
If efficiency is not a big concern, then regex is really sweet. See how:
public int getCount(String pattern) {
int patternCount = 0;
Matcher matcher = Pattern.compile(pattern).matcher(passedStrand);
while (matcher.find()) {
patternCount++;
}
return patternCount;
}

longest substring with exclude list of strings

I am using this algorithm to find common substring between 2 strings. Please, help me to do this but with using Array of common substrings of this strings, which I should ignore in my function.
My Code in Java:
public static String longestSubstring(String str1, String str2) {
StringBuilder sb = new StringBuilder();
if (str1 == null || str1.isEmpty() || str2 == null || str2.isEmpty()) {
return "";
}
// java initializes them already with 0
int[][] num = new int[str1.length()][str2.length()];
int maxlen = 0;
int lastSubsBegin = 0;
for (int i = 0; i < str1.length(); i++) {
for (int j = 0; j < str2.length(); j++) {
if (str1.charAt(i) == str2.charAt(j)) {
if ((i == 0) || (j == 0)) {
num[i][j] = 1;
} else {
num[i][j] = 1 + num[i - 1][j - 1];
}
if (num[i][j] > maxlen) {
maxlen = num[i][j];
// generate substring from str1 => i
int thisSubsBegin = i - num[i][j] + 1;
if (lastSubsBegin == thisSubsBegin) {
//if the current LCS is the same as the last time this block ran
sb.append(str1.charAt(i));
} else {
//this block resets the string builder if a different LCS is found
lastSubsBegin = thisSubsBegin;
sb = new StringBuilder();
sb.append(str1.substring(lastSubsBegin, i + 1));
}
}
}
}
}
return sb.toString();
}
So, my function should looks like:
public static String longestSubstring(String str1, String str2, String[] ignore)
Create a suffix tree of one of your strings and run through the second to see which substring can be found in the suffix tree.
Info on suffixtrees: http://en.wikipedia.org/wiki/Suffixtree
As far as I understand, you have to ignore those substrings that contain at least one string from ignore.
if (str1.charAt(i) == str2.charAt(j)) {
if ((i == 0) || (j == 0)) {
num[i][j] = 1;
} else {
num[i][j] = 1 + num[i - 1][j - 1];
}
// we must update `sb` on every step so that we can compare it with `ignore`
int thisSubsBegin = i - num[i][j] + 1;
if (lastSubsBegin == thisSubsBegin) {
sb.append(str1.charAt(i));
} else {
lastSubsBegin = thisSubsBegin;
sb = new StringBuilder();
sb.append(str1.substring(lastSubsBegin, i + 1));
}
// check whether current substring contains any string from `ignore`,
// and if it does, find the longest one
int biggestIndex = -1;
for (String s : ignore) {
int startIndex = sb.lastIndexOf(s);
if (startIndex > biggestIndex) {
biggestIndex = startIndex;
}
}
//Then sb.substring(biggestIndex + 1) will not contain strings to be ignored
sb = sb.substring(biggestIndex + 1);
num[i][j] -= (biggestIndex + 1);
if (num[i][j] > maxlen) {
maxlen = num[i][j];
}
}
If you have to ignore those substrings that are exactly the same as any string in ignore,
then when the candidate for longest common substring is found, iterate over ignore and check whether there is current substring in it.

mirrorEnds puzzle gives no clue to error

I am attempting to solve a codingbat problem called mirrorEnds. My solution fails but I'm not getting any useful feedback from the site, only a failed test run:
And my code (I changed string to str cause I'm used to the problems with "str"):
public String mirrorEnds(String string) {
String str = string;
StringBuilder sb = new StringBuilder();
int beg = 0;
int end = str.length()-1;
while(beg < end)
{
if(str.charAt(beg)==str.charAt(end))
sb.append(str.substring(beg,beg+1));
else
break;
++beg;
--end;
}
if(beg==end)
return str;
else
return sb.toString();
}
Here's mine, for what it's worth (not much, I know, but I was writing it while you were finding the bug..)
private String mirrorEnds(String string) {
final char[] chars = string.toCharArray();
final int n = chars.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
if (chars[i] != chars[n - i - 1])
break;
sb.append(chars[i]);
}
return sb.toString();
}
Bah. I found it. Instance is "abba"
Needed to change "if(beg==end)" to "if(beg>=end)".
public String mirrorEnds(String string) {
String s = "";
String str = "";
for (int i=string.length()-1; i>=0; i--)
{
s = s + string.charAt(i);
}
for (int j=0; j<string.length(); j++)
{
if (s.charAt(j) == string.charAt(j))
{
str = str + string.charAt(j);
}
if (s.charAt(j) != string.charAt(j))
{
break;
}
}
return str;
}
public static String mirrorEnds(String string) {
for (int i = 0; i < string.length(); i++) {
if(string.charAt(i) != string.charAt(string.length()-i-1)){
return string.substring(0,i);
}
else if(i==string.length()-1) return string;
}
return "";
}
Making a helper method is both efficient and makes the job easier, and logic clearer, recommended strategy for beginners, dissect the logic out, then put it together, as seen in codingBat's fizzBuzz questions that build up to the real fizzBuzz. Even though there a shorter solutions, this shows the full extent of logic used.
public String mirrorEnds(String string) {
String reversed = reverseString(string); //the reversed version
String result = "";
for(int a = 0; a < string.length(); a++){
if(string.charAt(a) == reversed.charAt(a)){ //keep going...
result += string.charAt(a);
}
else if(string.charAt(a) != reversed.charAt(a)){
break; //error, stop
}
}
return result;
}
public String reverseString(String s){
String reversed = "";
for(int a = s.length() - 1; a >= 0; a--){
reversed += s.charAt(a);
}
return reversed;
}
Here is mine:
public String mirrorEnds(String str) {
String res = "";
int count = str.length() - 1;
for(int i = 0;i < str.length();i++)
{
if(str.charAt(i) == str.charAt(count))
res += str.substring(i, i + 1);
else
break;
count--;
}
return res;
}
Here's my solution, hope it can help you
public String mirrorEnds(String string) {
int mid = string.length() / 2;
String s = "";
for (int i = 0, j = string.length()-1; i <= mid; i++, j--) {
if (i == mid) {
return string;
}
if (string.charAt(i) == string.charAt(j)) {
s += string.charAt(i) + "";
} else {
break;
}
}
return s;
}
Here's mine. I did mine a little bit different.
public String mirrorEnds(String string) {
//Create a string that we will eventually return.
String ret = "";
//Create a for loop that takes in chars from both ends.
for (int i = 0; i < string.length(); i++)
{
//Create one and two characters in order to simplify it.
char one = string.charAt(i);
char two = string.charAt(string.length() - 1 - i);
//If the front and back character in the iteration
//equal each other, then we add the character to the return string.
if (one == two)
{
ret = ret + one;
}
//Otherwise, we end the loop because we don't want to
//Have a loopback problem.
else
{
break;
}
}
//Return the string that we are working on.
return ret;
}

Categories