Interview Question
Country: United States
String data = "abcdefsdbcdefghmnxyz";
StringBuffer result = new StringBuffer();
StringBuffer temp = new StringBuffer();
for(int i=0; i< data.length(); i++){
int startIdx = i;
while((i+1< data.length()) && (data.charAt(i)+1 == data.charAt(i+1))){
i++;
}
if(startIdx != i){
temp.append(data.substring(startIdx, i+1));
if(temp.length() > result.length()){
result = temp;
}
temp = new StringBuffer();
}
}
System.out.println(result);
public String longestConsecutiveString(String target){
int tail = 0 , max = 0 ;
String rst = "" ;
for (int i = 1 ; i < target.length() ; ++i) {
if (target.charAt(i) - target.charAt(i -1) != 1) {
if (i - tail > max) {
max = i - tail ;
rst = target.substring(tail, i) ;
}
tail = i ;
}
}
return rst ;
}
Java solution:
public String findLongestAlphabet(String s){
final int n = s.length();
StringBuilder builder = new StringBuilder();
builder.append(s.charAt(0));
String ans = builder.toString();
for (int i = 1; i < n; i++){
if (s.charAt(i) != s.charAt(i - 1) + 1){
builder.setLength(0);
}
builder.append(s.charAt(i));
if (builder.length() > ans.length()){
ans = builder.toString();
}
}
return ans;
}
def find_longest (inp_string):
start = 0
max_count = 0
max_start = 0
count = 0
i = 1
while i < len(inp_string):
print (inp_string[i])
if ( ord(inp_string[i-1]) == ord(inp_string[i])-1):
count = count + 1
if (count > max_count):
max_count = count
max_start = start
else:
count = 0
start = i
i = i + 1
print (inp_string[max_start:max_start+max_count+1])
public class ContinousString {
- sourabhmehta83 March 04, 2015public static void main(String args [])
{
String str ="asdfihjasdabcdefhsdjfaabcdefghijfkas";
String constr = "";
String finalst="";
int i;
for(i=0;i<(str.length()-1);i++){
if(str.charAt(i)+1==((str.charAt(i+1)+1)-1)){
constr+=str.charAt(i);
if(finalst.length()<=constr.length()){
finalst=constr;
finalst+=str.charAt(i+1);
}
}
else{
constr="";
}
}
System.out.println(finalst);
}
}