簡體   English   中英

我的第一個非重復字符算法的缺陷在哪里?

[英]Where is the flaw in my algorithm for first non-repeated character?

在工作面試中,我遇到了在線編碼測試的這些問題,下周我被拒絕了。 我試圖弄清楚我做錯了什么還是我做錯了什么,但是C#具有更好的方法來完成相同的任務。

Q2)編寫一種方法來查找字符串中的第一個非重復字符。

a)要寫下您的答案,您可以使用任何喜歡的語言。 但是,如果您的語言已經具有庫,則您可能無法使用這些庫。

b)字符串是字母和小寫字母。 (例如,“ aaaabbbcccdde”->'e',“ abcdefgh”->'a',“ aaabbbcccddd”-> null,“ aabccdeef”->'b')

我的答案:

public char? FirstNonrepeatingChar ( String s ) 
{
    // returns the first non-repeated character in s
    // returns null if no such character exists
 for ( int j = 0, n = s.Length;  j < n ; )
   {
         int i = j;
         while ( j < n && s[j] == s[i] ) ++j;    
         if ( (j - i) == 1 ) return s[i]; // found lone character
    }
    return null; // if made it here, no such character exists
}

查找第一個不可重復的字符只是查找string[x-1] != string[x] && string[x] != string[x+1] 您的解決方案可以工作,但在邏輯上可以簡化:

if( String.IsNullOrEmpty(s) ) return null;
if( s.Length == 1 ) return s[0]; // Case 1: single-character string

if( s[0] != s[1] ) return s[0]; // Case 2: first character is different

for(int i = 1; i < s.Length - 1; i++) {

    // Main case 3: a sequence "aba" somewhere in the middle of the string
    if( s[i-1] != s[i] && s[i] != s[i+1] ) return s[i];
}

// Case 4: last character is different
if( s[ s.Length - 2 ] != s[ s.Length - 1 ] ) return s[ s.Length - 1 ];

// Case 5: Not found
return null;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM