Golang solution


  • 0
    A

    Here is a solution for the problem in Go.

    func characterReplacement(s string, k int) int {
    	var (
    		max, l int
    	)
    	count := make([]int, 128)
    
    	for r := 0; r < len(s); r++ {
    		count[s[r]]++
    		if max < count[s[r]] {
    			max = count[s[r]]
    		}
    
    		if r-l+1-max > k {
    			count[s[l]]--
    			l++
    		}
    	}
    
    	return len(s) - l
    }
    

    And the test case:

    func TestCharacterReplacement(t *testing.T) {
    	defer func() {
    		if r := recover(); r != nil {
    			if _, ok := r.(runtime.Error); ok {
    				t.Errorf("Panic: %v\n", r)
    				// debug.PrintStack()
    			}
    		}
    	}()
    
    	s := "ABAB"
    	k := 2
    	expected := 4
    
    	if r := characterReplacement(s, k); r != expected {
    		t.Errorf("Result for %s is wrong. got: %d, expected: %d\n", s, r, expected)
    	}
    
    	s = "AABABBA"
    	k = 1
    
    	if r := characterReplacement(s, k); r != expected {
    		t.Errorf("Result for %s is wrong. got: %d, expected: %d\n", s, r, expected)
    	}
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.