How to read an element in an array and see if it matches with a target string despite double letters -
so i'm trying find amount of times string present in array. if had array of {ab, abbbb, aaaabbb, ac} , had target string of ab, frequency of string ab 3 in array. program disregard repeating abbbb , aaaabbbb , read these element ab. have code changing duplicated sequence non-repeating sequence , comparing target if statement, it's not working , i'm not sure why. `it returning 0 value, when there should number.
this code:
public static int findfreqwithmutations (string target, string [] arr) { int count=0; (string s:arr) { string ans= ""; (int i=0; i<s.length()-1; i++) { if (s.charat(i) != s.charat(i+1)) { ans= ans + s.charat(i); } } if (ans == target) { count++; } } return count; } `
i'm going make assumption java context clues.
looks you're getting wrapped in searching string character character. take advantage of string.contains
, stream api
public static int findfreqwithmutations (string target, string[] arr) { return arrays.stream(arr) .maptoint(item -> item.contains(target) ? 1 : 0) .sum(); }
edit
charles brought point, don't have enough context know if ab should considered hit on aaabbbccc perhaps abc applicable hit. futhermore, ab wouldn't hit aaabbbccc string compiles down abc.
if case, here's alternative approach maps each string string distinct characters.
public static int occurrences(string[] array, string target) { return arrays.stream(array) .map(item -> item.codepoints().distinct().collect(stringbuilder::new, stringbuilder::appendcodepoint, stringbuilder::append).tostring()) .maptoint(item -> item.equals(target) ? 1 : 0) .sum(); }
Comments
Post a Comment