Bloomberg LP Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Written Test
It is good and efficient, O(N), but at line 17, there is no variable called 'i' because it was only available in the for() loop and destroyed after leaving the context of the for loop. I think the "int i=1" should be put before the for.
import java.util.*;
public class Maxpattern{
public static Map findmaxpattern(String str){
Map map = new TreeMap();
for(int i=0;i<str.length();i++){
int count =1;
if(map.containsKey(str.charAt(i))){
count = (int)map.get(str.charAt(i))+1;
map.put(str.charAt(i),count);
}else{
map.put(str.charAt(i),count);
}
}
return map;
}
public static void main(String [] args){
Map<String,Integer> list = findmaxpattern("aabbbbbbbbbcccdddddddddd");
int max=0;
for (Map.Entry<String,Integer> entry : list.entrySet()) {
{
if(entry.getValue()>max){
max=entry.getValue();
}
}
}
System.out.println("Maximum number of occurrence: "+max);
}
}
import java.util.*;
public class Maxpattern{
public static Map findmaxpattern(String str){
Map map = new TreeMap();
for(int i=0;i<str.length();i++){
int count =1;
if(map.containsKey(str.charAt(i))){
count = (int)map.get(str.charAt(i))+1;
map.put(str.charAt(i),count);
}else{
map.put(str.charAt(i),count);
}
}
return map;
}
public static void main(String [] args){
Map<String,Integer> list = findmaxpattern("aabbbbbbbbbcccdddddddddd");
int max=0;
for (Map.Entry<String,Integer> entry : list.entrySet()) {
{
if(entry.getValue()>max){
max=entry.getValue();
}
}
}
System.out.println("Maximum number of occurrence: "+max);
}
}
public static void run(String str)
{
char runChar = str.charAt(0);
String result = "";
int currentRun = 1;
int maxRun = 1;
int i=0;
for( i=1;i<str.length();i++)
{
if(str.charAt(i) == str.charAt(i-1))
{
currentRun++;
if(currentRun > maxRun)
{
maxRun = currentRun;
runChar = str.charAt(i-1);
}
}
else
{
currentRun = 1;
}
}
for(i=0;i<maxRun;i++)
{
result = result+runChar;
}
System.out.println(maxRun);
System.out.println(result);
}
if(str.length < 1 ) //rubbish;
char c=str[0]; //character of current run
char max_c=c; //character of maximum run
int pos=0; //position (index) of beginning of current run
int max_run=1; //length of maximum run
for(int i=1; i<str.length; i++)
{
if(str[i] != c) { //we've exited a run
if(i-pos > max_run) max_run=i-pos, max_c=c; //update max info if needed
c=str[i], pos=i; //regardless, mark the start of new run
}
for(int i=0; i<max_run; i++) putchar(max_c);
Using Hashmap ---> time complexity is O(n)
private static String getCharRUn(String str)
{
Map<Character, Integer> charMap = new LinkedHashMap<Character, Integer>();
for(int i = 0; i < str.length(); i++)
{
if(charMap.containsKey(str.charAt(i)) == false)
{
charMap.put(str.charAt(i), 1);
}
else
{
charMap.put(str.charAt(i), charMap.get(str.charAt(i)) + 1);
}
}
int j = 1, max = 0;
char maxChar = ' ';
StringBuffer result = new StringBuffer();
for(Character c : charMap.keySet())
{
if(charMap.get(c) > max)
{
max = charMap.get(c);
maxChar = c;
}
}
while(j <= max)
{
result.append(maxChar);
j++;
}
return result.toString();
}
public class longestrunstring {
public static void main(String args[]){
String a = args[0];
int max = 0;
char longest = ' ';
int count = 1;
if(a.length() >0){
for(int i = 1; i < a.length() - 1;i++){
if(a.charAt(i) == a.charAt(i+1)){
count++;
}
else {
if(count+1 > max){
max = count+1;
longest = a.charAt(i);
}
count = 0;
}
}
if(count+1 > max){
max = count+1;
longest = a.charAt(a.length()-1);
}
if(max == 0){
max = count+1;
longest = a.charAt(0);
}
}
for (int i = 0;i< max;i++)
System.out.print(longest);
}
}
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
char str[30] = "ssggggddhhhhh";
char out = str[0];
int count = 1;
char m = out;
int ma = count;
for (int i = 1; i <= strlen(str); i++)
{
if(out == str[i])
count++;
else
{
count = 1;
}
//printf("%d",count);
out = str[i];
//printf("%c",out);
if(count > ma){
ma = count;
m = out;
}
}
for (int i = 0; i < ma; i++)
{
printf("%c",m);
}
getchar();
}
void longestRep(string s) {
if(s.length() == 0)
return;
//string substr (size_t pos = 0, size_t len = npos) const;
string rst = s.substr(0, 1);
string tmp = rst;
for(int i = 1; i < s.size(); i++) {
if(s[i] == s[i - 1]) {
tmp += s[i];
}
else{
tmp.clear();
tmp += s[i];
}
rst = tmp.size() > rst.size() ? tmp : rst;
}
cout<<rst<<endl;
}
void print_runs(string s) {
map<char,int> themap;
string::iterator it = s.begin();
char current = *it;
int run = 1;
++it;
for (;
it != s.end();
++it) {
if (*it == current)
++run;
else {
if (themap[current] < run)
themap[current] = run;
run = 0;
current = *it;
}
}
map<char,int>::iterator i;
int print = 0;
std::pair<char,int> ret;
for (i = themap.begin();
i != themap.end();
++i) {
if ((*i).second > print) {
print = (*i).second;
ret.first = (*i).first;
ret.second = (*i).second;
}
}
cout << ret.first << " " << ret.second << " ";
for (int j = 0; j < ret.second; ++j)
cout << ret.first;
cout << endl;
}
public static void calcLongest () {
String text = "aabbbccaaadddde";
char ch = 0;
if ( text.length() > 0 ) {
int longestIndexStart = 0;
int longestLength = 1;
int currIndexStart = 0;
int currLength = 1;
ch = text.charAt(0);
for ( int i = 1 ; i < text.length(); ++i ) {
if ( text.charAt(i) == ch ) {
currLength++;
} else {
ch = text.charAt(i);
if (currLength > longestLength) {
longestIndexStart = currIndexStart;
longestLength = currLength;
}
currIndexStart = i;
currLength = 1;
}
}
System.out.println(longestIndexStart + "\t" + longestLength);
System.out.println( text.substring(longestIndexStart, longestIndexStart + longestLength ) );
}
}
There is a small error in the above code. It won't count the last character if that's the part of longest repeated sequence. Here is the correct code. Tested for all input data.
public static void calcLongest () {
String [] texts = {"a" , "aab" , "aa" , "abbbbbcc" , "aabbccdd" , "aabbbccaaadddde"};
for (String text : texts) {
char ch = 0;
if ( text.length() > 0 ) {
int longestIndexStart = 0;
int longestLength = 1;
int currIndexStart = 0;
int currLength = 1;
ch = text.charAt(0);
for ( int i = 1 ; i < text.length(); ++i ) {
if ( text.charAt(i) == ch ) {
currLength++;
} else {
ch = text.charAt(i);
if (currLength > longestLength) {
longestIndexStart = currIndexStart;
longestLength = currLength;
}
currIndexStart = i;
currLength = 1;
}
}
if ( currLength > longestLength ) {
longestIndexStart = currIndexStart;
longestLength = currLength;
}
System.out.println( text + " --> " + text.substring(longestIndexStart, longestIndexStart + longestLength ) );
}
}
}
char* longest_run(char* in)
{
int highest_count = 1;
int i_count=1;
char prev = in[0];
char final = prev;
int cur=1;
while(in[cur] != '\0')
{
if(in[cur] == prev)
{
i_count++;
if(highest_count < i_count)
{
highest_count = i_count;
final = prev;
}
}
else
{
prev = in[cur];
i_count=1;
}
cur++;
}
char *out = (char*)malloc(highest_count+1);
out[highest_count] = '\0';
memset(out, final, highest_count);
return out;
}
My solution in Python.
Time complexity: O(n)
def solution(s):
# zm is a list of zeros to keep track of continuity
zm = [0 for _ in range(len(s))]
for i, c in enumerate(s):
if (i+1) < len(s):
if c == s[i+1]:
zm[i], zm[i+1] = 1, 1
seq = set()
seqs = []
for i, flag in enumerate(zm):
if flag == 1 and (i+1) < len(zm):
if (i+1) - i == 1:
seq.add(i)
if zm[i + 1] == 1:
seq.add(i+1)
else:
if len(tuple(seq)) > 0:
seqs.append(sorted(tuple(seq)))
seq = set()
lens = []
for seq in seqs:
lens.append(len(seq))
max_len = max(lens)
max_len_ind = lens.index(max_len)
start = seqs[max_len_ind][0]
end = seqs[max_len_ind][-1]
print s[start:end+1]
if __name__ == '__main__':
string = 'ehersdgfffghjhedeetyyyyy'
solution(string)
#include <iostream>
#include <string>
using namespace std;
int main() {
string mstr = "aaaaabbbccdd";
int nLen = mstr.size();
int nPStr = 0, nCStr = 0, nMax = 1, nCur = 1;
int i = 1;
while (i < nLen) {
if (mstr[i] == mstr[i - 1]) nCur++;
else {
if (nCur > nMax) {
nMax = nCur;
nPStr = nCStr;
}
nCStr = i;
nCur = 1;
}
i++;
}
cout << nMax << ", str = " << mstr.substr(nPStr, nMax) << endl;
cout << "Press enter to continue ..." << endl;
cin.get();
return 0;
}
#include <iostream>
#include <string>
using namespace std;
string getLongestRun(const string &str){
unsigned max_count =0;
size_t max_char_start_idx = 0;
for (size_t i=0; i<str.length(); ){
int count=1;
size_t j=i+1;
for ( ;j<str.length() && str[j] == str[i]; ++j){
++count;
}
if (count > max_count) {
max_count = count;
max_char_start_idx = i;
}
i = j;
}
return str.substr(max_char_start_idx, max_count);
}
int main(){
cout << getLongestRun("aaabbccbbbbdd") << endl;
cout << getLongestRun("aabbccbbdd") << endl;
cout << getLongestRun("aacd") << endl;
cout << getLongestRun("acd") << endl;
cout << getLongestRun("") << endl;
cout << getLongestRun("aacddd") << endl;
return 0;
}
Please comment the following code
int run(char a[], int size, char *maxchar, int *maxcount)
{
int count = 0;int i = 0;
if (*maxcount < 0)
return -1;
while (a[i] != '\0')
{
if (a[i] == a[i+1])
{
count++;
}
else if (*maxcount < count)
{
*maxchar = a[i];
*maxcount = count;
count = 0;
}
i++;
}
return 0;
}
public String getRun(String str){
char longestChar;
int longestLen=0;
Char[] cstr = str.toCharArray();
char nowChar = cstr[0];
int nowLen = 1;
longestChar = nowChar;
longestLen = nowLen;
for(int i=1; i<cstr.length; i++){
if(cstr[i]==nowChar){
nowLen++;
if(nowLen>longestLen){
longestChar = nowChar;
longestLen = nowLen;
}
}else{
nowChar = cstr[i];
nowLen= 1;
}
}
StringBuffer sb = new StringBuffer();
for(int i = 0 ; i<longestLen; i++){
sb.append(longestChar);
}
return sb.toString();
}
public static void printLongestRunString(String s){
char currentlastChar =s.charAt(0);
char longestchar = currentlastChar;
int longestRun=1;
int currentLongestRun =1;
for(int i=1; i< s.length(); i++){
char ch = s.charAt(i);
if(ch==currentlastChar){
currentLongestRun ++;
}
else{
if(currentLongestRun > longestRun){
longestRun = currentLongestRun;
longestchar = currentlastChar;
}
currentlastChar =ch;
currentLongestRun =1;
}
}
if(currentLongestRun > longestRun){
longestRun = currentLongestRun;
longestchar = currentlastChar;
}
for (int i = 0; i < longestRun; i++) {
System.out.print(longestchar);
}
}
$ g++ longestRun.cpp
$ ./a.exe
Run String: aaakdnndjfjfklaaaaaaeeejjfeefffewwwewwwwww
Max Run Char: a Max Count: 5
Run String: aaaaaa
Max Run Char: a Max Count: 6
$ cat longestRun.cpp
#include <iostream>
#include <string>
#include <string.h>
#include <map>
using namespace std;
void printLongestRun(string inputString)
{
int length=inputString.length();
char *inputStringChars=new char[length+1];
strcpy(inputStringChars,inputString.c_str());
inputStringChars[length]='\0';
// map<char,int> run;
char currentChar;
char previousChar=inputStringChars[0];
int charCount=0;
int maxCount=-1;
char maxChar;
for(int i=0;i<length;i++)
{
currentChar=inputStringChars[i];
if(currentChar == previousChar) { charCount++; continue;}
// map<char,int>::iterator it=run.find(previousChar);
// if((it != run.end() && run[previousChar] < charCount) || it == run.end())
// run[previousChar]=charCount;
if(maxCount < charCount) {maxCount=charCount;maxChar=previousChar;}
previousChar=currentChar;
charCount=0;
}
if(maxCount < charCount) {maxCount=charCount;maxChar=previousChar;}
cout<<"Run String: "<<inputString<<"\n";
cout<<"Max Run Char: " << maxChar << " Max Count: "<<maxCount<<"\n";
}
int main()
{
printLongestRun("aaakdnndjfjfklaaaaaaeeejjfeefffewwwewwwwww");
printLongestRun("aaaaaa");
return 0;
}
$
std::string longRun(std::string s)
{
if (s.empty()) return std::string(" ");
if (s.length() == 1) return s;
int maxRun = 1;
int maxIndex = 0;
int currRun = 1;
for (int i = 1; i < s.length(); i++) {
if (s.at(i) != s.at(i-1)) {
currRun = 1;
} else {
currRun++;
if (currRun > maxRun) {
maxRun = currRun;
maxIndex = i+1-currRun;
}
}
}
return std::string(maxRun, s.at(maxIndex));
}
void printLongRun(char*s){
if(s==null) return;
if(*s == '\0') return;
char bestChar = s[0];
char currentChar = s[0]
int maxRun = 1;
int run = 1;
s++;
while(*s) {
if(*s == bestChar) run++;
else {
if(run>maxRun) {
maxRun = run;
bestChar = currentChar;
}
currentChar = *s;
run = 1;
}
++s;
}
while(maxRun-- > 0) {
printf("%c", bestChar);
}
}
This one is mine:
std::string GetLongestRun(const std::string& sInput)
{
char chCurrent('\0'), chMax('\0');
std::size_t nChNum(0), nChMaxNum(0);
for(std::string::size_type pos = 0;pos<sInput.size();++pos)
{
if ( chCurrent!=sInput[pos] )
{
if ( nChNum>nChMaxNum )
{
chMax = chCurrent;
nChMaxNum = nChNum;
}
nChNum = 0;
chCurrent = sInput[pos];
}
++nChNum;
}
return nChMaxNum>nChNum ? std::string(nChMaxNum, chMax) : std::string(nChNum, chCurrent);
}
// This one does not use random access to char array elements,
// so it should be more efficient
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
if(argc!=2 || *argv[1]=='\0')
{
cout << "One argument: non-empty alfanumeric string" << endl;
return 1;
}
int maxcnt = 1; //maximum run count
char* str = argv[1];
int rcnt = 1; //current run count
char c = *(str++); //current character
char maxc = c; //maximum run character
while (*str != '\0')
{
if(*str==c)
rcnt++;
else
{
if(rcnt > maxcnt)
{
maxcnt=rcnt;
maxc=c;
}
rcnt=1;
}
c=*(str++);
}
if(rcnt > maxcnt)
{
maxcnt=rcnt;
maxc=c;
}
cout << string(maxcnt, maxc) << endl;
}
Hi everyone,
I use Python for this question:
i and j are used as a pointer to the index number of characters in the given string.
###############################
def LCS(s):
i,j = 0,1
ret = ''
if len(s)==0 or len(s)==1:
return s
else:
ret = s[i:j]
while(j < len(s)):
if s[i] != s[j] or s[j]== s[:-1]:
# move both index to the next one
if j-i == 1:
i += 1
j += 1
else:
if len(ret) < (j-i): # if return string doesn't have maximum length
ret = s[i:j]
i += (j-i)
j += 1
else:
# find duplicated character, beginning character (is at i) remains the same while
# j moves to the next index to compare with character at i
j += 1
if len(ret) < (j-i):
ret = s[i:j]
return ret
void printLongestRun(const string &str){
if (str.length() <=1) {
cout <<str<<"\n";
return;
}
unsigned cur =0, next=0, max =0, max_start =0;
while(str[cur]){
while (next < str.length() && str[cur] == str[next]) ++next;
unsigned end = (next != str.length()) ? next-1 : str.length()-1;
if (end - cur + 1 > max){
max = end - cur + 1;
max_start = cur;
}
cur = next;
}
cout << str << "\t=>"<<str.substr(max_start, max) << "\n";
}
void printLongestRun(const string &str){
if (str.length() <=1) {
cout <<str<<"\n";
return;
}
unsigned cur =0, next=0, max =0, max_start =0;
while(str[cur]){
while (next < str.length() && str[cur] == str[next]) ++next;
unsigned end = (next != str.length()) ? next-1 : str.length()-1;
if (end - cur + 1 > max){
max = end - cur + 1;
max_start = cur;
}
cur = next;
}
cout << str << "\t=>"<<str.substr(max_start, max) << "\n";
}
void printLongestRun(const string &str){
if (str.length() <=1) {
cout <<str<<"\n";
return;
}
unsigned cur =0, next=0, max =0, max_start =0;
while(str[cur]){
while (next < str.length() && str[cur] == str[next]) ++next;
unsigned end = (next != str.length()) ? next-1 : str.length()-1;
if (end - cur + 1 > max){
max = end - cur + 1;
max_start = cur;
}
cur = next;
}
cout << str << "\t=>"<<str.substr(max_start, max) << "\n";
}
public static String getLongestRun(String str){
Map<Character, Integer> map = new HashMap<Character, Integer>();
Character cur = str.charAt(0);
int count = 0;
for(int i=0; i<str.length(); i++){
if(str.charAt(i) == cur){
count++;
if(map.get(cur) == null){
map.put(cur, count);
}else{
if(map.get(cur) < count){
map.put(cur, count);
}
}
}else{
cur = str.charAt(i);
count = 0;
}
}
Character maxChar = null;
int maxCount = 0;
for(Character c : map.keySet()){
if(map.get(c) > maxCount){
maxCount = map.get(c);
maxChar = c;
}
}
for(int j=0; j<maxCount; j++){
System.out.print(maxChar);
}
return null;
}
static void Main(string[] args)
{
string s = Console.ReadLine();
char[] a = s.ToCharArray();
Dictionary<string, int> collection = new Dictionary<string, int>();
foreach (var i in a)
{
if (!collection.ContainsKey(i.ToString()))
{
collection.Add(i.ToString(), 1);
}
else
{
collection[i.ToString()] = collection[i.ToString()] + 1;
}
}
foreach (var item in collection.OrderByDescending(x => x.Value))
{
int x = item.Value;
while (x >= 1)
{
Console.Write(item.Key);
x -= 1;
}
Console.ReadKey();
return;
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class A{
public A() {
System.out.println("This is class A construtor");
}
public static void main(String args[])
{
System.out.println("Enter the String ");
try{
BufferedReader line = new BufferedReader(new InputStreamReader(System.in) );
String input = line.readLine();
input+=" ";
int maxvalue=0;
String result="",finalString="";
for (int i=0;i<input.length()-1;i++)
{
if(input.charAt(i)==input.charAt(i+1)){
result+=input.charAt(i);
}
else{
if(result.length()>maxvalue){
maxvalue=result.length();
finalString=result+input.charAt(i);
}
result="";
}
}
System.out.println("Result ="+finalString);
System.out.println("Result length ="+finalString.length());
}
catch(Exception e){
System.out.println("Exception Occured ="+e.getMessage());
e.printStackTrace();
}
}
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* getLongestRun(char []);
int main()
{
char *str=getLongestRun("abbbbbccdd");
printf("\n%s\n",str);
str=getLongestRun("aaabbccbbbbdd");
printf("\n%s\n",str);
str=getLongestRun("aabbccbbdd");
printf("\n%s\n",str);
str=getLongestRun("aacd");
printf("\n%s\n",str);
str=getLongestRun("aacddd");
printf("\n%s\n",str);
return 0;
}
char* getLongestRun(char s[])
{
if(!s)
{
printf("String is NULL,System exiting\n");
exit(0);
}
int length=strlen(s);
if(length==0)
{
printf("string is empty,System exiting\n");
exit(0);
}
char *str=(char *)malloc(sizeof(length+1));
int i=0,count=0,max=1,j=0;
int start_index_count=0,end_index_count=0;
for(i=0;i<length;i++)
{
count=1;
for(j=i;j<length;j++)
{
if(s[j]==s[j+1])
{
count++;
}
else
{
break;
}
}
if(count>max)
{
start_index_count=i;
end_index_count=j;
max=count;
}
}
printf("Longest run count is %d",max);
for(i=start_index_count,j=0;i<=end_index_count;i++,j++)
*(str+j)=s[i];
return str;
}
#include <stdio.h>
int main()
{
int currentNumberOfOcc=1, previousNumberOfOcc =1, i=0;
char inputString[200], currentChar=-1, previousChar=-1;
printf ("Enter the string = ");
fgets(inputString, 200, stdin);
for(i=0; i < strlen(inputString); i++)
{
currentChar = inputString[i];
if (currentChar == inputString[i+1])
{
currentNumberOfOcc++;
}
else
{
if (currentNumberOfOcc >= previousNumberOfOcc && inputString[i+1]
!=NULL)
{
previousNumberOfOcc = currentNumberOfOcc;
previousChar = currentChar;
}
currentNumberOfOcc =1;
}
}
for (i =0;i< previousNumberOfOcc; i++)
{
printf ("%c",previousChar);
}
printf ("\n");
}
I solved problem in java,
public static void main(String[] args){
Scanner in= new Scanner(System.in);
String s= in.next();
ArrayList<Character> currentLogest=new ArrayList<>();
ArrayList<Character> current=new ArrayList<>();
int lengtOfcurrentLongest=0, currentLength=0;
char prev = s.toCharArray()[0];
for(char c : s.toCharArray()){
if(prev==c)
{
current.add(c);
prev=c;
if(current.size()>currentLogest.size())
{
currentLogest=new ArrayList<>();
currentLogest=current;
}
}
else
{
current=new ArrayList<>();
current.add(c);
prev=c;
System.out.println(current);
if(current.size()>currentLogest.size()){
currentLogest=new ArrayList<>();
currentLogest=current;
}
}
}
System.out.println("Size: " + currentLogest.size() + " longest run: " + currentLogest );
}
I used C++11:
#include <iostream>
using namespace std;
int main() {
string s = "kaasssaaddddee";
int start = 0, end = 0, temp_start = 0, temp_end = 0;
int i = 0;
for(i = 1;i < s.length();i++){
if(s[i] == s[temp_start]) temp_end++;
else{
if(temp_end - temp_start > end - start){
start = temp_start;
end = temp_end;
}
temp_start = i;
temp_end = i;
}
}
cout << s.substr(start, end - start + 1);
return 0;
}
The previous code fails if the part with maximum number of characters is at the and of the string. Here's how it can be fixed:
#include <iostream>
using namespace std;
int main() {
string s = "kaasssaaddddeejjjjjj";
int start = 0, end = 0, temp_start = 0, temp_end = 0;
int i = 0;
for(i = 1;i < s.length();i++){
if(s[i] == s[temp_start]){
temp_end++;
if(temp_end - temp_start > end - start){
start = temp_start;
end = temp_end;
}
}
else{
if(temp_end - temp_start > end - start){
start = temp_start;
end = temp_end;
}
temp_start = i;
temp_end = i;
}
}
cout << s.substr(start, end - start + 1);
return 0;
}
void LongestRun(const string &s)
{
char run_char = ' ';
int max_count = 0;
int curr_count = 0;
char ch = ' ';
for (int i = 0; i < s.length(); i++)
{
if (s[i] != ch)
curr_count = 0;
curr_count++;
ch = s[i];
if (curr_count > max_count)
{
run_char = ch;
max_count = curr_count;
}
}
for (int i = 0; i < max_count; i++)
cout << run_char;
cout << endl;
}
void LongestRun(const string &s)
{
char run_char = ' ';
int max_count = 0;
int curr_count = 0;
char ch = ' ';
for (int i = 0; i < s.length(); i++)
{
if (s[i] != ch)
curr_count = 0;
curr_count++;
ch = s[i];
if (curr_count > max_count)
{
run_char = ch;
max_count = curr_count;
}
}
for (int i = 0; i < max_count; i++)
cout << run_char;
cout << endl;
}
#include<stdio.h>
#include<string.h>
int main()
{
char a[]="abbbbbbbbcccccyyyyyyyyy";
a[strlen(a)]='\0';
int i,j=0;
int first=0;
int last=0;
int count=1;
int max=0;
for(i=0;i<strlen(a);i++)
{
if(a[i]!=a[i+1])
{
if(count>max)
{
first=j;
last=i;
max=count;
}
j=i+1;
count=1;
}
else
count++;
}
printf("\n");
for(i=first;i<=last;i++)
printf("%c", a[i]);
}
std::string getLongestRun(const std::string& str)
{
char longestRunChar = str[0];
unsigned int length = 1;
char currLongestRunChar = str[0];
unsigned int currLength = 1;
char prevChar = str[0];
for (int index = 1; index < str.length(); ++index)
{
if (str[index] == prevChar)
{
++currLength;
}
else
{
if (currLength > length)
{
length = currLength;
longestRunChar = currLongestRunChar;
}
currLongestRunChar = str[index];
currLength = 1;
}
prevChar = str[index];
}
return string(length, longestRunChar);
}
It seems alot of this code is unnecessarily complex. This is what I did:
std::string longest_run(std::string s){
std::string cur = "";
cur += s[0];
std::string max = cur;
for(int i = 1; i < s.size(); i++){
if(s[i] == cur.back()) cur += s[i];
else cur = s[i];
if(cur.size() > max.size()) max = cur;
}
return max;
}
public static String getLongestRun(String s){
int i = 0, j = 1;
String tempString = s.substring(0, 1);
for(i = 0; i < s.length() && j < s.length();){
while(j < s.length() && s.charAt(i) == s.charAt(j))
{
j++;
}
//System.out.println("i = " + i + " j = " + j + " temp = " + s.substring(i, j));
if(tempString.length() < (j-i))
{
//System.out.println("Changed");
tempString = s.substring(i, j);
}
//System.out.println(tempString);
i = j;
j++;
}
return tempString;
}
#include <stdio.h>
char *longest_run(char *str) {
char *index = str, max_char = *str, curr_char;
int curr_run, max_run = 1;
while (*index != '\0') {
curr_char = *index;
curr_run = 0;
while (*index == curr_char) {
index++;
curr_run++;
}
if (curr_run > max_run) {
max_run = curr_run;
max_char = curr_char;
}
}
index = str;
while (max_run > 0) {
*index++ = max_char;
max_run--;
}
*index = '\0';
return str;
}
int main() {
char str[] = "aabbccccddcc";
printf(longest_run(str));
printf("\n");
return 0;
}
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
printLongest("abbbbcc");
}
public static void printLongest(String s)
{
char ch = s.charAt(0), maxCh=s.charAt(0);
int max = 0;
int counter = 1;
for(int i=1; i < s.length(); i++)
{
char c = s.charAt(i);
if(c == ch)
counter++;
else
{
if(counter>max)
{
max = counter;
maxCh = ch;
}
counter = 1;
ch = c;
}
if(i==s.length()-1)
{
if(counter>max)
{
max = counter;
maxCh = ch;
}
}
}
for(int i = 0; i < max; i++)
{
System.out.print(maxCh);
}
}
}
public String longestRun(String str) {
int maxLen = 1;
int maxStart = 0;
int curStart = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) != str.charAt(curStart)) {
if (i - curStart > maxLen) {
maxLen = i - curStart;
maxStart = curStart;
}
curStart = i;
}
}
return str.substring(maxStart, maxStart + maxLen);
}
public String longestRun(String str) {
int maxLen = 1;
int maxStart = 0;
int curStart = 0;
for (int i = 0; i <= str.length(); i++)
{
if (i==str.length() || str.charAt(i) != str.charAt(curStart))
{
if (i - curStart > maxLen) {
maxLen = i - curStart;
maxStart = curStart;
}
curStart = i;
}
//else if(maxStart==0 && curStart==0)
//maxLen++;
}
return str.substring(maxStart, maxStart+maxLen);
}
In addition to the bug pointed out by yx, the task was to write a "program", not just a function, and to "print" the longest run.
@igorfact: Seriously, that is your concern? You can't write a program yourself, given that function?
- Anonymous March 06, 2014