Wednesday, July 23, 2008

string and arrays

char firstNonrepeatedChar(string s):
    Hashmap h
    flag seenOnce
    flag seenTwice
    for (int i = 0; i < s.length; i++):
        x = h.get(s[i]) 
        if x = null:
            h.put(s[i], seenOnce)
        else:
            if x = seenOnce:
                h.put(s[i], seenTwice) 
    for (int i = 0; i < s.length; i++): 
        if h.contains(s[i]) = seenOnce: 
            return s[i]
    return null

--

string removeSpecifiedChars(string s, string remove): 
    /* use flags[128] if s and remove consists only of ASCII */
    Hashmap h 
    for (int i = 0; i < remove.length; i++): 
        h.put(remove[i], true) 
    source = 0 
    dest = 0 
    while (source < s.length): 
        if h.get(s[source]) = true:
            source++
        else:
            s[dest] = s[source]
            source++
            dest++
    return string(s[0 .. dest-1])

--

While reversing the words in a string, there are some things to look for. 'this test', '  test  ' would be some examples to check for. We find the start and end positions of a word and then reverse it. 

reverseWords(char[] s):
    start, end = 0
    while (start < s.Length):
        while (start < s.Length && a[start] == ' '):
            start++
        end = start
        while (end < s.Length && a[end] != ' '):
            end++
        end--
        reverse(s, start, end)
        start = end +1
    

reverse(char[] s, int start, int end):
    if 0 <= start < s.Length && 0 <= end < s.Length:
        while start < end:
            temp = s[start]
            s[start] = s[end]
            s[end] = temp
            start++
            end-- 


[Hat tip to PIE]

No comments:

Post a Comment