Using java, input string="aabbcdeaaaabbb" and the output must be aaaa -
using java, input string="aabbcdeaaaabbb" , output must aaaa, sequence here having repeated 4 times a. can me "aaaa" output using java implementation.
algorithm find longest substring having same character repeated.
for eg:
i/p: aabbcdefaaaacccccc o/p: cccccc
please check program below , suggest optimization faster processing:
public class longestsubstring { public static void main(string[] args) throws ioexception { bufferedreader reader = new bufferedreader(new inputstreamreader( system.in)); system.out .println("enter word find longest substring same characters repeated"); string word = reader.readline(); system.out.println("entered word is: " + word); system.out.println("longest repeated characters substring is: " + substringfinder(word)); } /* *longest substring finder same character repeated */ public static string substringfinder(string word) { char[] tokens = word.tochararray(); int len = tokens.length; int wordlen = word.length(); system.out.println("len of input word: " + wordlen); list<string> mylist = new arraylist<>(); stringbuilder strconcat = new stringbuilder(""); (int j = 0; j <= len - 1; j++) { if (j + 1 > len - 1) { if ((strconcat.length() >= 1) && (strconcat.charat(strconcat.length() - 1) == (tokens[j]))) { strconcat.append("" + tokens[j]); mylist.add(strconcat.tostring()); } } else { if (tokens[j] == tokens[j + 1]) { if ((strconcat.length() >= 1) && (strconcat.charat(strconcat.length() - 1) == (tokens[j]))) { strconcat.append("" + tokens[j]); mylist.add(strconcat.tostring()); } else { strconcat = new stringbuilder(""); strconcat.append("" + tokens[j]); } } else { if ((strconcat.length() >= 1) && (strconcat.charat(strconcat.length() - 1) == (tokens[j]))) { strconcat.append("" + tokens[j]); mylist.add(strconcat.tostring()); } else { strconcat = new stringbuilder(""); strconcat.append("" + tokens[j]); } } } } int max = 0, index = 0; (int = 0; < mylist.size(); i++) { string strele = mylist.get(i); int strlen = strele.length(); if (max < strlen) { max = strlen; index = i; } } return mylist.get(index); } }
i believe code overly complicated. don’t need stringbuilder
nor arraylist
. tried understand intention, skipped , wrote own version instead. hope helps anyway.
public static string substringfinder(string word) { if (word == null || word.isempty()) { return word; } char currentchar = word.charat(0); int longeststart = 0; int longestlength = 0; int currentstart = 0; int currentlength = 1; (int ix = 1; ix < word.length(); ix++) { if (word.charat(ix) == currentchar) { currentlength++; } else { if (currentlength > longestlength) { longeststart = currentstart; longestlength = currentlength; } currentchar = word.charat(ix); currentstart = ix; currentlength = 1; } } if (currentlength > longestlength) { longeststart = currentstart; longestlength = currentlength; } return word.substring(longeststart, longeststart + longestlength); }
Comments
Post a Comment