Amdocs Interview Question
Developer Program EngineersCountry: United States
public class FindConcecutiveCharacter {
public static String[] findConcecutive(String[] arr) {
String temp = null;
int len=arr.length;
String[] finalArray = new String[len];
for(int i=0;i<len;i++){
char[] temparr=arr[i].toCharArray();
for(int j=0;j<temparr.length-1;j++){
if(temparr[j]==temparr[j+1]){
finalArray[i]=arr[i];
}
}
}
return finalArray;
}
public static void main(String[] args) {
String [] array={"hello","robot","summer","elephant"};
String [] array1=findConcecutive(array);
for(int i=0;i<array1.length;i++){
System.out.println(array1[i]);
}
}
}
public class AmdocsInterviewQuestionDeveloperProgramEngineers {
public static void main(String[] args) {
String[] wordArray = {"hello", "robot", "summer", "elephant"};
System.out.println(Arrays.toString(repeatChars(wordArray)));
}
private static String[] repeatChars(String[] wordArray) {
List<String> result = new LinkedList<String>();
//
for (String word : wordArray) {
for (int i = 1; i < word.length(); i++) {
if (word.charAt(i - 1) == word.charAt(i)) {
result.add(word);
break;
}
}
}
//
return result.toArray(new String[result.size()]);
}
}
Usage:
python consecutivechars.py hello,robot,summer,elephant
hello
summer
Script:
#!/usr/bin/env python
import sys
def has_consecutive(word, prev_ch):
if not word:
return False
elif word[0] == prev_ch:
return True
else:
return has_consecutive(word[1:], word[0])
if __name__ == '__main__':
if len(sys.argv) < 2:
sys.exit(2)
words = [word.strip() for word in sys.argv[1].split(',') if word.strip()]
print '\n'.join([word for word in words if has_consecutive(word, '')])
Could be optimized in C easily for efficiency, to have an array of pointers of all word beginnings (NULL truncate each, in place), and recurse on &word[1] and word[0] in has_consecutive instead of using the list operations in Python.
/*
Problem: Return an array of strings that have repeated characters together
*/
public static String[] findConsecutiveCharacters(String[] arr)
{
ArrayList<String> arrayList = new ArrayList<>();
for (int i = 0; i < arr.length; i++)
{
String s = arr[i];
for (int j = 0; j < s.length() - 1; j++) {
if (s.charAt(j + 1) == s.charAt(j)) {
arrayList.add(arr[i]);
}
}
}
return arrayList.toArray(new String[arrayList.size()]);
}
Similar solution to another poster here but I used ArrayList append so there aren't so many nulls in the final result array. This solution has a similar algorithm to what appears in Cracking the Coding Interview on Problem 1.5 Encode String.
- Juan July 25, 2014