[英]Find the length of the longest substring with no consecutive repeating characters
In a recent interview, I was asked this to find the length of the longest sub-string with no consecutive repeating characters. 在最近的一次采访中,我被要求查找没有连续重复字符的最长子字符串的长度。 This is different from the standard question, since it considers only consecutive repeating characters.
这与标准问题不同,因为它仅考虑连续的重复字符。
For example : 例如 :
WOOD : 2
Italics : 7
This, of course, has to be done in O(N) time and space. 当然,这必须在O(N)时空中完成。
Go down the string character by character. 逐个字符地向下键入字符串。 Keep track of how many characters you've advanced without hitting a repeat in a var say "repeatcounter".
跟踪您前进了多少个字符,而无需在变体中重复说“ repeatcounter”。 If the next character matches the current character record the counter in a separate variable (only if it's bigger than what's already in there) and reset the repeatcounter.
如果下一个字符与当前字符匹配,则将计数器记录在一个单独的变量中(仅当其大于那里已有的字符时),然后重置重复计数器。
In Python, I would approach it like this: 在Python中,我会这样处理:
def interview(s):
current = longest = 0
for index, char in enumerate(s):
if index and char == s[index - 1]:
longest, current = max(longest, current), 0
current += 1
return max(longest, current)
public static void main(String[] args){
String s = "italics";
char[] c = s.toCharArray();
int tmp = 1;
for (int i = 1; i < s.length(); i++) {
if (c[i] == c[i-1]){
tmp = 0;
continue;
}
tmp++;
}
System.out.println(tmp);
}
output = 1 输出= 1
s = "italics" s =“斜体”
output = 7 输出= 7
Hope the below code helps you. 希望下面的代码对您有所帮助。 Thanks.
谢谢。
import java.util.HashSet;
public class SubString {
public static String subString(String input){
HashSet<Character> set = new HashSet<Character>();
String longestOverAll = "";
String longestTillNow = "";
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (set.contains(c)) {
longestTillNow = "";
set.clear();
}
longestTillNow += c;
set.add(c);
if (longestTillNow.length() > longestOverAll.length()) {
longestOverAll = longestTillNow;
}
}
return longestOverAll;
}
public static void main(String[] args) {
String input = "kaveeshkanwal abcvdghytrqp";//"substringfindout";
System.out.println(subString(input));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.