Last active
January 8, 2016 19:45
-
-
Save SIRHAMY/25f2fe34129d98c007f2 to your computer and use it in GitHub Desktop.
Finds and returns the longest sequence of consecutive characters (as per ASCII) in given string.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class LongestCharSeq { | |
public String findLongest(String s) { | |
StringBuffer result = new StringBuffer(); | |
s.toLowerCase(); | |
int lastChar = getAsciiVal(s.charAt(0)) - 1; | |
StringBuffer currentSeq = new StringBuffer(); | |
for(int i = 0; i<s.length(); i++) { | |
int currChar = (int) s.charAt(i); | |
if(currChar == lastChar + 1) { | |
currentSeq.append(s.charAt(i)); | |
} else { | |
if(currentSeq.length() > result.length() && currentSeq.length() > 1) { | |
result = currentSeq; | |
} | |
currentSeq = new StringBuffer(); | |
} | |
lastChar = currChar; | |
} | |
if(currentSeq.length() > result.length() && currentSeq.length() > 1) result = currentSeq; | |
return result.toString(); | |
} | |
public int getAsciiVal(char c) { | |
return (int) c; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment