給定一個字符串,請你找出其中不含有重復字符的 最長子串 的長度


題目:

   給定一個字符串,請你找出其中不含有重復字符的 最長子串 的長度。

題目解析:

   有一個字符串,長度不定, 要找出不重復字符串的長度,我們可以這么假設,先找到第一個下標,然后從后面拿到元素的下標對比,如果不等,就取到下一個元素的下標。如果相等,就取前一元素的下標。最后截取字符串的長度 計算。

    python代碼實現:

    

def finstr(findstr:str):
    for i in range(len(findstr)):
        for j in range(len(findstr)):
            data = findstr[0:i]
            if str(findstr[j])  in str(data):
                m=findstr[0:i]
            else:
                m=findstr[0:j+1]
    return len(m)

 

  測試代碼:
  
from sixexapmle import finstr
import  unittest
class Test(unittest.TestCase):
    def setUp(self) -> None:pass
    def tearDown(self) -> None:pass
    def testone(self):
        reslut=finstr("0")
        self.assertEqual(1,reslut)
    def testtewo(self):
        reslut=finstr("01")
        self.assertEqual(2,reslut)
    def testthree(self):
        reslut=finstr("011")
        self.assertEqual(2,reslut)
if __name__=="__main__":
    unittest.main()

 

    測試結果:

    代碼覆蓋率:

其實實現起來不難,

我們來看下java版本的實現:

代碼:

  

public class Five {
    public  Integer maxstr(String max){
        String m="";
        for (int a = 0; a < max.length(); a++) {
            String n=max.substring(0,a);
            for (int b = 0; b < max.length(); b++) {
                if (n.indexOf(max.substring(b))!=-1 ){
                    m=max.substring(0,b);
                }else {
                    m=max.substring(0,a+1);
                }
            }
        }
        return m.length();
    }
}

 

測試代碼:

 

public class FiveTest {

    @Test
    public void testMaxstr() {
            Five five=new Five();
            assertEquals(five.maxstr("12").intValue(),2);
    }
    @Test
    public void testMaxstr1() {
        Five five=new Five();
        assertEquals(five.maxstr("1").intValue(),1);
    }
    @Test
    public void testMaxstr2() {
        Five five=new Five();
        assertEquals(five.maxstr("121").intValue(),2);
    }
}

 

  測試結果:

​覆蓋率:

自此,上面完成的就是本題。

 注:這是提供一種思路方案,實現方式千萬種。​


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM