Encuentra el número de mayor longitud en una string

Dada una string de dígitos y caracteres. Escriba un programa para encontrar el número con el número máximo de dígitos en una string. 
Nota: Es posible que el número no sea el mayor de la string. Por ejemplo, si la string es «a123bc321», la respuesta puede ser 123 o 321, ya que el problema es encontrar el número con la longitud más larga y no el valor más grande.
Ejemplos: 
 

Input: geeks100for1234geeks
Output: 1234

Input: abx12321bst1234yz
Output: 12321

Enfoque: la idea es recorrer la string y, si se encuentra un dígito, almacenar su posición y desde esa posición recorrer más hasta que aparezca un carácter. Cada vez que se encuentre una serie continua de un dígito, almacene su longitud y combínela con la longitud previamente encontrada en la serie de un dígito para encontrar el máximo de todas las series continuas de dígitos.
A continuación se muestra la implementación del enfoque anterior. 
 

C++

// C++ code for finding the longest
// length integer
#include <iostream>
using namespace std;
 
string longestInteger(string str, int l)
{
    int count = 0, max = 0, pos = -1, pre_pos, pre_len, len = 0;
    // Traverse the string
    for (int i = 0; i < l; i++) {
        // Store the previous position and previous length
        // of the digits encountered.
        pre_pos = pos;
        pre_len = len;
        count = 0;
        len = 0;
 
        // If first digit occurs, store its position in pos
        if (isdigit(str[i]))
            pos = i;
 
        // Traverse the string till a character occurs.
        while (isdigit(str[i])) {
            count++;
            i++;
            len++;
        }
 
        // Check if the length of the string is
        // greater than the previous ones or not.
        if (count > max) {
            max = count;
        }
        else {
            pos = pre_pos;
            len = pre_len;
        }
    }
    return (str.substr(pos, len));
}
 
// Driver code
int main()
{
    string str = "geeks100for1234geeks";
    int l = str.length();
    cout << longestInteger(str, l);
    return 0;
}

Java

// Java code for finding the
// longest length integer
import java.io.*;
import java.util.*;
import java.lang.*;
 
class GFG
{
static String longestInteger(String str, int l)
{
    int count = 0, max = 0,
        pos = -1, pre_pos,
        pre_len, len = 0;
     
    // Traverse the string
    for (int i = 0; i < l; i++)
    {
        // Store the previous position
        // and previous length of the
        // digits encountered.
        pre_pos = pos;
        pre_len = len;
        count = 0;
        len = 0;
 
        // If first digit occurs,
        // store its position in pos
        if (Character.isDigit(str.charAt(i)))
            pos = i;
 
        // Traverse the string
        // till a character occurs.
        while (Character.isDigit(str.charAt(i)))
        {
            count++;
            i++;
            len++;
        }
 
        // Check if the length of
        // the string is greater
        // than the previous ones
        // or not.
        if (count > max)
        {
            max = count;
        }
        else
        {
            pos = pre_pos;
            len = pre_len;
        }
    }
    return (str.substring(pos, pos + len));
}
 
// Driver code
public static void main(String[] args)
{
    String str = "geeks100for1234geeks";
    int l = str.length();
    System.out.print(longestInteger(str, l));
}
}

C#

// C# code for finding the
// longest length integer
using System;
 
class GFG
{
static string longestInteger(string str,
                             int l)
{
    int count = 0, max = 0,
        pos = -1, pre_pos,
        pre_len, len = 0;
     
    // Traverse the string
    for (int i = 0; i < l; i++)
    {
        // Store the previous position
        // and previous length of the
        // digits encountered.
        pre_pos = pos;
        pre_len = len;
        count = 0;
        len = 0;
 
        // If first digit occurs,
        // store its position in pos
        if (Char.IsDigit(str[i]))
            pos = i;
 
        // Traverse the string
        // till a character occurs.
        while (Char.IsDigit(str[i]))
        {
            count++;
            i++;
            len++;
        }
 
        // Check if the length of
        // the string is greater
        // than the previous ones
        // or not.
        if (count > max)
        {
            max = count;
        }
        else
        {
            pos = pre_pos;
            len = pre_len;
        }
    }
    return (str.Substring(pos, len));
}
 
// Driver code
public static void Main()
{
    string str = "geeks100for1234geeks";
    int l = str.Length;
    Console.Write(longestInteger(str, l));
}
}
 
// This code is contributed
// by ChitraNayal

Python 3

# Python 3 code for finding the
# longest length integer
 
def longestInteger(s, length):
    count = 0
    maximum = 0
    pos = -1
    l = 0
     
    # Traverse the string
    for i in range(length):
         
        # Store the previous position
        # and previous length of
        # the digits encountered.
        pre_pos = pos
        pre_len = l
        count = 0
        l = 0
 
        # If first digit occurs,
        # store its position in pos
        if (s[i].isdecimal()):
            pos = i
 
        # Traverse the string
        # till a character occurs.
        while (s[i].isdecimal()):
            count += 1
            i += 1
            l += 1
 
        # Check if the length of
        # the string is greater
        # than the previous ones
        # or not.
        if (count > maximum):
            maximum = count
         
        else:
            pos = pre_pos
            l = pre_len
 
    return (s[pos: pos + l])
 
# Driver code
s = "geeks100for1234geeks"
length = len(s)
print(longestInteger(s, length))
 
# This code is contributed
# by ChitraNayal

PHP

<?php
// PHP code for finding the
// longest length integer
 
function longestInteger($str, $l)
{
    $count = 0;
    $max = 0;
    $pos = -1;
    $pre_pos = 0;
    $pre_len = 0;
    $len = 0;
     
    // Traverse the string
    for ($i = 0; $i < $l; $i++)
    {
        // Store the previous position
        // and previous length of
        // the digits encountered.
        $pre_pos = $pos;
        $pre_len = $len;
        $count = 0;
        $len = 0;
 
        // If first digit occurs,
        // store its position in pos
        if (is_numeric($str[$i]))
            $pos = $i;
 
        // Traverse the string till
        // a character occurs.
        while (is_numeric($str[$i]))
        {
            $count++;
            $i++;
            $len++;
        }
 
        // Check if the length of
        // the string is greater
        // than the previous ones
        // or not.
        if ($count > $max)
        {
            $max = $count;
        }
        else
        {
            $pos = $pre_pos;
            $len = $pre_len;
        }
    }
    return (substr($str, $pos, $len));
}
 
// Driver code
$str = "geeks100for1234geeks";
$l = strlen($str);
echo longestInteger($str, $l);
 
// This code is contributed
// by ChitraNayal
?>

Javascript

<script>
// Javascript code for finding the
// longest length integer
     
    function longestInteger(str,l)
    {
        let count = 0, max = 0,
        pos = -1, pre_pos,
        pre_len, len = 0;
       
    // Traverse the string
    for (let i = 0; i < l; i++)
    {
        // Store the previous position
        // and previous length of the
        // digits encountered.
        pre_pos = pos;
        pre_len = len;
        count = 0;
        len = 0;
   
        // If first digit occurs,
        // store its position in pos
        if (!isNaN(String(str[i]) * 1))
            pos = i;
   
        // Traverse the string
        // till a character occurs.
        while (!isNaN(String(str[i]) * 1))
        {
            count++;
            i++;
            len++;
        }
   
        // Check if the length of
        // the string is greater
        // than the previous ones
        // or not.
        if (count > max)
        {
            max = count;
        }
        else
        {
            pos = pre_pos;
            len = pre_len;
        }
    }
    return (str.substring(pos, pos + len));
    }
     
    // Driver code
    let str = "geeks100for1234geeks";
    let l = str.length;
    document.write(longestInteger(str, l));
     
 
// This code is contributed by rag2127
</script>
Producción: 

1234

 

Complejidad de Tiempo: O(n) 
Complejidad de Espacio Auxiliar: O(1)
 

Publicación traducida automáticamente

Artículo escrito por Smitha Dinesh Semwal y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *