代码之家  ›  专栏  ›  技术社区  ›  Gagantous Faradox

如何检查单词php中的第一个副本?

php
  •  0
  • Gagantous Faradox  · 技术社区  · 6 年前

    我有这个词。

    AGHIJKLAL
    

    我需要搜索 第一个重复单词 从这个字符串中,答案是 A 因为在这些句子中重复的单词是 单词。

    例如。

    输入0

    JKLMKL
    

    输出0

    K
    

    输入1

    nmopqrqn
    

    输出1

    q
    

    我做了这个节目。

    <?php 
    
    $input = fgets(STDIN);
    $rows = str_split(trim($input));
    $arr = array();
    $index = 0;
    
    while (True) {
        $reset = False;
        $ind = 0;
        foreach ($rows as $row => $val) {
        if(!isset($rows[$row+1])){
            continue;
        }
          if($rows[0] !== $rows[$row+1]) {
            $reset = True;
            continue;
          } else {
              $reset = True;
              $arr[$index] = $rows[0];
              $index++;
              break;
          }
        }
        if (!$reset) {
            break; # break out of the while(true)
        }else{
            unset($rows[0]);
            $rows = array_values($rows);
        }
        # otherwise the foreach loop is `reset`
    }
    
    echo "{$arr[0]} \n";
    
    ?>
    

    但当我使用 输入1 值,它返回 n 价值。我的代码有什么问题?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Bhaskar Jain    6 年前

    首先,使用 str_split() 检查每个字符。

    //convert string into array
    $strArr = str_split('AGHIJKLAL'); 
    
    $temp = []; //temporary array  
    foreach($strArr as $v){
        //check each character if it is in temp array or  not, if yes, character matched and exit from loop using break; 
        if(in_array($v, $temp)){
            $repeatChar = $v;
            break;
        }else{ // if not matched store character into temp array.
            $temp[] = $v;
        }
    }
    echo $repeatChar;
    

    Demo

    推荐文章