Skip to content

Instantly share code, notes, and snippets.

@SIRHAMY
Last active January 8, 2016 19:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SIRHAMY/25f2fe34129d98c007f2 to your computer and use it in GitHub Desktop.
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.
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