По заданной строке найдите второй по частоте символ в ней. Ожидаемая сложность по времени составляет O (n), где n — длина входной строки.
Примеры:
Input: str = "aabababa";
Output: Second most frequent character is 'b'
Input: str = "geeksforgeeks";
Output: Second most frequent character is 'g'
Input: str = "geeksquiz";
Output: Second most frequent character is 'g'
The output can also be any other character with
count 1 like 'z', 'i'.
Input: str = "abcd";
Output: No Second most frequent character
Простое решение — начать с первого символа, сосчитать его вхождения, затем второй символ и так далее. При подсчете этих случаев следите за максимальными и вторыми максимальными значениями. Временная сложность этого решения составляет O (n 2 ).
Мы можем решить эту проблему за O (n) время, используя массив count с размером, равным 256 (при условии, что символы хранятся в формате ASCII). Ниже приводится реализация подхода.
C ++
#include <bits/stdc++.h>
using namespace std;
#define NO_OF_CHARS 256
char getSecondMostFreq(string str)
{
int count[NO_OF_CHARS] = {0}, i;
for (i = 0; str[i]; i++)
(count[str[i]])++;
int first = 0, second = 0;
for (i = 0; i < NO_OF_CHARS; i++)
{
if (count[i] > count[first])
{
second = first;
first = i;
}
else if (count[i] > count[second] &&
count[i] != count[first])
second = i;
}
return second;
}
int main()
{
string str = "geeksforgeeks" ;
char res = getSecondMostFreq(str);
if (res != '\0' )
cout << "Second most frequent char is " << res;
else
cout << "No second most frequent character" ;
return 0;
}
|
С
#include <stdio.h> #define NO_OF_CHARS 256
char getSecondMostFreq( char *str)
{
int count[NO_OF_CHARS] = {0}, i;
for (i=0; str[i]; i++)
(count[str[i]])++;
int first = 0, second = 0;
for (i = 0; i < NO_OF_CHARS; i++)
{
if (count[i] > count[first])
{
second = first;
first = i;
}
else if (count[i] > count[second] &&
count[i] != count[first])
second = i;
}
return second;
}
int main()
{
char str[] = "geeksforgeeks" ;
char res = getSecondMostFreq(str);
if (res != '\0' )
printf ( "Second most frequent char is %c" , res);
else
printf ( "No second most frequent character" );
return 0;
}
|
Джава
public class GFG
{
static final int NO_OF_CHARS = 256 ;
static char getSecondMostFreq(String str)
{
int [] count = new int [NO_OF_CHARS];
int i;
for (i= 0 ; i< str.length(); i++)
(count[str.charAt(i)])++;
int first = 0 , second = 0 ;
for (i = 0 ; i < NO_OF_CHARS; i++)
{
if (count[i] > count[first])
{
second = first;
first = i;
}
else if (count[i] > count[second] &&
count[i] != count[first])
second = i;
}
return ( char )second;
}
public static void main(String args[])
{
String str = "geeksforgeeks" ;
char res = getSecondMostFreq(str);
if (res != '\0' )
System.out.println( "Second most frequent char" +
" is " + res);
else
System.out.println( "No second most frequent" +
"character" );
}
}
|
Python 3
def getSecondMostFreq( str ) :
NO_OF_CHARS = 256
count = [ 0 ] * NO_OF_CHARS
for i in range ( len ( str )) :
count[ ord ( str [i])] + = 1
first, second = 0 , 0
for i in range (NO_OF_CHARS) :
if count[i] > count[first] :
second = first
first = i
elif (count[i] > count[second] and
count[i] ! = count[first] ) :
second = i
return chr (second)
if __name__ = = "__main__" :
str = "geeksforgeeks"
res = getSecondMostFreq( str )
if res ! = '\0' :
print ( "Second most frequent char is" , res)
else :
print ( "No second most frequent character" )
|
C #
using System;
public class GFG {
static int NO_OF_CHARS = 256;
static char getSecondMostFreq( string str)
{
int []count = new int [NO_OF_CHARS];
for ( int i = 0; i < str.Length; i++)
(count[str[i]])++;
int first = 0, second = 0;
for ( int i = 0; i < NO_OF_CHARS; i++)
{
if (count[i] > count[first])
{
second = first;
first = i;
}
else if (count[i] > count[second] &&
count[i] != count[first])
second = i;
}
return ( char )second;
}
public static void Main()
{
string str = "geeksforgeeks" ;
char res = getSecondMostFreq(str);
if (res != '\0' )
Console.Write( "Second most frequent char" +
" is " + res);
else
Console.Write( "No second most frequent" +
"character" );
}
}
|
PHP
<?php
$NO_OF_CHARS =256;
function getSecondMostFreq( $str )
{
global $NO_OF_CHARS ;
$count = array_fill (0, $NO_OF_CHARS ,0);
for ( $i = 0; $i < strlen ( $str ); $i ++)
$count [ord( $str [ $i ])]++;
$first = $second = 0;
for ( $i = 0; $i < $NO_OF_CHARS ; $i ++)
{
if ( $count [ $i ] > $count [ $first ])
{
$second = $first ;
$first = $i ;
}
else if ( $count [ $i ] > $count [ $second ] &&
$count [ $i ] != $count [ $first ])
$second = $i ;
}
return chr ( $second );
}
$str = "geeksforgeeks" ;
$res = getSecondMostFreq( $str );
if ( strlen ( $res ))
echo "Second most frequent char is " . $res ;
else
echo "No second most frequent character" ;
?>
|
Выход:
Second most frequent char is g
Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по обсуждаемой теме
Рекомендуемые посты:
Программа для поиска второго по частоте персонажа
0.00 (0%) 0 votes